【发布时间】:2010-08-31 06:57:06
【问题描述】:
我必须存储不同 boost::function 对象的列表。为了提供这个,我使用了 boost::any。我有一些函数采用不同的函数签名,将它们打包到 any 中,然后插入到具有给定类型的特殊映射中。代码如下:
enum TypeEnumerator
{
e_int,
e_float,
e_double
};
typedef map< string, pair<any, TypeEnumerator> > CallbackType;
CallbackType mCallbacks;
void Foo(const string &name, function<float ()> f)
{
mCallbacks[name] = make_pair(any(f), CLASS::e_float);
}
void Foo(const string &name, function<int ()> f) { /* the same, but with e_int */ }
void Foo(const string &name, function<double ()> f) { /* the same, but with e_double */ }
现在我有地图增强功能,用枚举中的给定类型打包到 any 中,以便将来识别它。现在我必须调用给定的函数。来自 any 的铸造不起作用:
BOOST_FOREACH(CallbackType::value_type &row, mCallbacks)
{
// pair<any, TypeEnumerator>
switch (row.second.second) // Swith the TypeEnumerator
{
case 0: // int
any_cast< function<int ()> >(row.first)();
break;
case 1: // float
any_cast< function<float ()> >(row.first)();
break;
case 2: // double
any_cast< function<double ()> >(row.first)();
break;
}
}
这不会强制转换,并且在运行期间出现异常:
what(): boost::bad_any_cast: failed conversion using boost::any_cast
是否可以转换回 boost::function 对象?
【问题讨论】:
-
您是否在
case 1中忘记了break? -
@KennyTM 是的,但它仍然失败。
标签: c++ casting boost-function any