我必须存储一个不同的boost :: function对象的列表。为了提供这个我使用boost :: 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 */ }
现在我已经在地图升压功能,包装成与枚举类型给出任何,要认识到它的未来。现在我必须调用给定的函数。从任何铸造将无法正常工作:
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 ::功能对象?
你是否忘记了'case 1'中的'break'? – kennytm 2010-08-31 07:05:09
@KennyTM是的,但它仍然失败。 – Ockonal 2010-08-31 07:09:01