[英]Reuse function call with argument of different possible types in c++
I am wondering if there is a way to reuse the call to the function template_fun
in the following c++ code. 我想知道是否有一种方法可以在以下c ++代码中重用对函数
template_fun
的调用。
#include <iostream>
#include <cstdlib>
#include <ctime>
template <typename T>
double template_fun(T arg)
{
double a = 1.1;
a += (double)arg;
return a;
}
int main()
{
std::srand(std::time(0));
int r = std::rand() % 2;
double out;
switch(r)
{
case 0:
{
int arg = 1;
out = template_fun(arg);
break;
}
case 1:
{
double arg = 1.2;
out = template_fun(arg);
break;
}
}
std::cout << out << "\n";
}
Since the line out = template_fun(arg);
由于该行
out = template_fun(arg);
is repeated, I was hoping there was a way to reuse it somehow. 重复一遍,我希望有一种以某种方式重用它的方法。 Obviously, this issue of calling a template function with different input data types depending on an input is really what I'm getting at.
显然,这个问题取决于我根据输入调用具有不同输入数据类型的模板函数的问题。 The code I'm working on is much more complex.
我正在处理的代码要复杂得多。 I am not particularly hopeful for a clever solution, since it would probably mean defining the data type of
arg
at runtime. 对于一个聪明的解决方案,我并不特别希望,因为这可能意味着在运行时定义
arg
的数据类型。 But perhaps I am missing something. 但是也许我错过了一些东西。
Thank you in advance for your help! 预先感谢您的帮助! Much appreciated.
非常感激。
You may use some variant
class, and do something like: 您可以使用一些
variant
类,并执行以下操作:
struct template_fun : boost::static_visitor<double>
{
template <typename T>
double operator() (T arg) const
{
double a = 1.1;
a += (double)arg;
return a;
}
};
int main()
{
std::srand(std::time(0));
int r = std::rand() % 2;
boost::variant<int, double> arg;
double out = 0.0;
switch(r)
{
case 0: { arg = 1; break; }
case 1: { arg = 1.2; break; }
}
out = boost::apply_visitor(template_fun{}, arg);
std::cout << out << "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.