我想知道是否有办法在以下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";
}
由于重复了out = template_fun(arg);
行,我希望有办法以某种方式重用它。显然,根据输入调用具有不同输入数据类型的模板函数的问题实际上是我所得到的。我正在处理的代码要复杂得多。我并不特别希望有一个聪明的解决方案,因为它可能意味着在运行时定义arg
的数据类型。但也许我错过了一些东西。
提前感谢您的帮助!非常感谢。
答案 0 :(得分:0)
您可以使用某些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";
}