代码之家  ›  专栏  ›  技术社区  ›  Georg Fritzsche

从成员函数指针类型生成函数子

  •  5
  • Georg Fritzsche  · 技术社区  · 17 年前

    我试图简化(通过 make_fn() )预处理参数的functor的生成(通过 wrap() n .
    生成functor基本上是有效的,但到目前为止,只能通过显式指定成员函数的参数类型。

    struct X {};
    
    template<class C, typename T1, bool (C::*F)(T1)>
    inline // there are more for T1..TN
    bool wrap(C* c, X x) 
    {
        return (c->*F)(process<T1>(x));
    }
    
    template<class C, typename T1, bool (C::*F)(T1)> 
    inline // there are more for T1..TN
    boost::function<bool (C*, X)> make_fn(F f) // <- problem here, F is not a type
    {
        return boost::bind(&wrap<C, T1, F>, _1, _2);
    }
    

    然而,vc++和g++看不到 F

    这个想法是,它应该这样工作:

    struct A 
    {
        bool f1(bool) { return true; }
    };
    
    void test()
    {
        A a;
        X x;
        make_fn(&A::f1)(&a, x);
    }
    

    你有什么想法吗?


    bool invoke(C* c, const char* const functionName, int argCount, X* args);
    



    包装的目的是避免手动转换,而是生成为我或 throw

    1 回复  |  直到 17 年前
        1
  •  3
  •   UncleBens    17 年前

    在我看来,您正试图将传递给函数的指针转换为非类型模板参数,恐怕这行不通(请参阅您问题的注释)。

    您可以做的是将函数指针存储在函数对象中。以下内容似乎可以编译:

    #include <boost/bind.hpp>
    #include <boost/function.hpp>
    
    struct X {};
    
    template <class T>
    bool process(X) { return true; }
    
    
    template <class C, class T1, class Func>
    struct wrap1
    {
        typedef bool result_type;
        Func f;
    
        wrap1(Func f): f(f) {}
    
        bool operator()(C* c, X x)
        {
            return (c->*f)(process<T1>(x));
        }
    };
    
    template<class C, typename T1>
    inline // there are more for T1..TN
    boost::function<bool (C*, X)> make_fn(bool (C::*f)(T1))
    {
        return boost::bind(wrap1<C, T1, bool (C::*)(T1)>(f), _1, _2);
    }
    
    
    struct A
    {
        bool f1(bool) { return true; }
    };
    
    void test()
    {
        A a;
        X x;
        make_fn(&A::f1)(&a, x);
    }
    

    然而,我不确定这是否有什么好处,以及你将如何创建其余的包装器。对于后者,您可能只会得到一个支持可变模板的编译器。 :)