代码之家  ›  专栏  ›  技术社区  ›  user152508

带模板运算符()的任意函子的boost函数

  •  0
  • user152508  · 技术社区  · 7 年前

    我想储存 boost::function<void(void*)>

    struct MyFunctor
    {
        template<class T>
        void operator()(T* a)
        {            
            T& ref = *a; 
    
        } 
    };
    struct MyFunctor2
    {
        template<class T>
        void operator()(T* a)
        {            
            T& ref = *a; 
    
        } 
    };
    
    boost::function<void(void*)> anyFunctorPtr;
    anyFunctorPtr= MyFunctor();
    double a = 5;   
    anyFunctorPtr(&a);
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   Max Langhof    7 年前

    boost::function ,就像 std::function 需要特定的函子签名(在您的情况下 void(void*) T 推断为 void 编译器拒绝给你一个 void&

    您的示例从根本上说是增加了自身的可能性,因为如果您想进行类型擦除,就不能有模板,因为编译器不知道以其他方式实例化哪些模板。假设一下 boost::function<magic> 我可以做你想做的。

    void foo(boost::function<magic> func)
    {
        double a = 5;   
        func(&a);
    }
    

    编译器如何知道是否生成 T = double MyFunctor MyFunctor2 ? 它根本不知道,因此无法生成正确的代码。对于可以拥有的模板函子类的数量和可以尝试调用的类型的数量没有限制 operator()