是否可以编写一个根据模板类型而变化的函数?
我正在尝试创建一个可以生成随机变量的类。我希望能够在运行时根据模板化值生成任何随机类型。我想我可以通过对每个数据类型进行专门编码,使这个函数适用于整数、字符串和双精度数据类型来实现这一点。
template <typename T>
class Generator{
private:
int upper_bound;
int lower_bound;
int size;
vector<T> data;
vector<int> keys;
public:
Generator(int size, int lower_bound, int upper_bound){
this->size = size;
this->upper_bound = upper_bound;
this->lower_bound = lower_bound;
}
void generate_keys(){
//key generater
int rand_num;
int row = 0;
//uses srand and rand to get generator random keys and random data
srand(time(0));
cout << "Generating the keys now..." << endl;
cout << "upper bound - " << get_upper_bound() << endl;
for(int i=0;i < size;i++){
//rand_num = dist(rng);
rand_num = (rand()%upper_bound)+lower_bound;
cout << rand_num << " ";
keys.push_back(rand_num);
row++;
if(row == 3){
cout << endl;
row = 0;
}
}
cout << endl;
}
//templated so this function can work with strings, doubles, and ints
void generate_data(){
}
I'm trying to create a class that can generate a random variable. I want to be able to generate any random type based on the templated value at runtime. I figured I can do this by making this function works for ints, strings, and double data types by coding each one specifically.
template <typename T>
class Generator{
private:
int upper_bound;
int lower_bound;
int size;
vector<T> data;
vector<int> keys;
public:
Generator(int size, int lower_bound, int upper_bound){
this->size = size;
this->upper_bound = upper_bound;
this->lower_bound = lower_bound;
}
void generate_keys(){
//key generater
int rand_num;
int row = 0;
//uses srand and rand to get generator random keys and random data
srand(time(0));
cout << "Generating the keys now..." << endl;
cout << "upper bound - " << get_upper_bound() << endl;
for(int i=0;i < size;i++){
//rand_num = dist(rng);
rand_num = (rand()%upper_bound)+lower_bound;
cout << rand_num << " ";
keys.push_back(rand_num);
row++;
if(row == 3){
cout << endl;
row = 0;
}
}
cout << endl;
}
//templated so this function can work with strings, doubles, and ints
void generate_data(){
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用模板专业化来生成不同数据类型的随机数。
使用此代码逻辑进行浮点随机数生成
You can use template specialization for generating random numbers in different data types.
use this code logic for floating-point random number generation