我使用 boost::any 成功保存了变量,但不知道它们的类型。但我想知道是否可以在不实际将它们转换回原始类型的情况下使用它们。这是一个可以更好地描述问题的示例:
struct callbackInfo
{
boost::any pointer_to_the_object;
boost::any pointer_to_the_function;
};
class someClass
{
template<class T, class P>
void add(T const func, P that)
{
callbackInfo tmp;
tmp.pointer_to_the_object =that;
tmp.pointer_to_the_function = func;
functions->addLast(tmp);
}
template<class ARG>
void trigger(SENDERTYPE sender, ARG arg)
{
STLinkedListIterator<callbackInfo>* it = functions->createIteator();
if(it != nullptr)
{
do
{
//This is the problem:
((*it->getData().pointer_to_the_object).*it->getData().pointer_to_the_function)(nullptr);
it->next();
}while(!it->EOL());
}
}
}
我想我已经知道答案是否定的,因为编译无法检查变量的类型,但无论如何我想也许有一个天才的解决方案。
最佳答案
您可以将 boost::any
视为更类型安全的 void*
,它可以指任何内容,但除非您知道它指的是什么并且可以正确地将其转换回来,您几乎无能为力。
由于您真正想要存储的是一个对象和一个指向成员函数的指针,然后调用它,因此您不需要使用完全通用的 boost::any
您可以创建一个调用包装器将这两个东西绑定(bind)在一起,然后使用允许存储和调用函数的东西,而 Boost 正是您所需要的:
struct callbackInfo {
boost::function<void(void*)> func;
};
template<class T, class P>
void add(T func, P that)
{
callbackInfo tmp = { boost::bind(func, that, _1) };
functions->addLast(tmp);
}
// ...
it->getData().func(nullptr);
关于c++ boost::any 在不知道类型的情况下使用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16917746/