c++ boost::any 在不知道类型的情况下使用值

标签 c++ class pointers

我使用 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/

相关文章:

c++ - C++11 中的 C 风格回调

php - 从同一类中的静态方法访问另一个方法中的变量

c# - 删除 C# 不安全指针

c++ - 将 3D 指针数组传递给函数

iphone - 指针困惑

c++ - 尝试在结构构造函数上引用已删除的函数

c++ - 分配大块连续内存——做还是不做?

c++ - boost::join 和 boost::transformed

c++ - 类的常量成员变量可以在方法而不是构造函数中初始化吗?

php - fatal error : Call to undefined method stdClass