[英]Reuse function call with argument of different possible types in c++
我想知道是否有一種方法可以在以下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
的數據類型。 但是也許我錯過了一些東西。
預先感謝您的幫助! 非常感激。
您可以使用一些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.