0 c++ boost boost-variant c++11
我有一个有模板的类:
template<class T = int> class slider;
Run Code Online (Sandbox Code Playgroud)
该类有一个void Process(void)方法,所以,我认为它应该是可调用的类型,返回值是无效的,并且没有参数.
至于现在我有这个代码来调用我的应用程序中的每个帧的进程:
//class menu:
typedef boost::variant<std::shared_ptr<slider<int>>,std::shared_ptr<slider<float>>,std::shared_ptr<slider<double>>,std::shared_ptr<slider<char>>> slider_type;
std::map<std::string,slider_type> Sliders;
//buttons ... etc ...
void Process()
{
if(!Sliders.empty())
{
for(auto i = Sliders.begin(); i != Sliders.end(); ++i)
{
switch(i->second.which())
{
case 0://slider<int>
{
boost::get<std::shared_ptr<slider<int>>>(i->second)->Process();
break;
}
case 1://slider<float>
{
boost::get<std::shared_ptr<slider<float>>>(i->second)->Process();
break;
}
//.....
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以执行函数Process(),如下例所示?
for(auto i = Sliders.begin(); i != Sliders.end(); ++i)
{
switch(i->second.which())
{
boost::get<???Any???>(i->second)->Process();
}
}
Run Code Online (Sandbox Code Playgroud)
如果有,怎么样?
这样的函数会返回什么?您无法在运行时更改函数的类型.变体的要点是它的内容是在运行时确定的.
它唯一能回归的是一个boost::any.这真的只是将一种未知的东西换成另一种(当你不知道它包含什么时,一个未知的难以处理,请注意).但是如果你想看到这样的访客:
struct convert_to_any : public boost::static_visitor<boost::any>
{
template<typename T> boost::any operator() (const T& t) {return t;}
};
Run Code Online (Sandbox Code Playgroud)
使用apply_visitor它,你会得到一个any回来.虽然我没有看到这有多大帮助.
无论如何,如果你正在使用geta variant,你几乎肯定做错了.访问变体元素的正确方法是访问者,而不是访问者get.
在您的情况下,访问者应该很简单:
struct ProcessVisitor : public boost::static_visitor<>
{
template<typename T> void operator() (const T& t) const {t->Process();}
};
Run Code Online (Sandbox Code Playgroud)
就这样使用吧apply_visitor.如果变量包含可以使用的类型,operator->并且该函数的返回值可以Process调用它,那么它将会.