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

带成员函数指针的模板元编程?

  •  1
  • wheaties  · 技术社区  · 16 年前

    是否可以在模板元编程中使用成员函数指针?例如:

    class Connection{
    public:
        string getName() const;
        string getAlias() const;
    //more stuff
    };
    
    typedef string (Connection::*Con_Func)() const;
    
    template<Con_Func _Name>
    class Foo{
        Connection m_Connect;
    public:
        Foo(){
            cout << (m_Connect.*_Name)();
        }
    };
    
    typedef Foo<&Connection::getName> NamedFoo;
    typedef Foo<&Connection::getAlias> AliasFoo;
    

    2 回复  |  直到 16 年前
        1
  •  2
  •   luke    16 年前

    退房 this discussion 关于指向作为模板参数的非静态成员的指针。看起来VC++实现有问题。

        2
  •  2
  •   BenMorel Manish Pradhan    12 年前

    // Necessary includes
    #include <string>
    #include <iostream>
    #include <ostream>
    
    class Connection{
    public:
            // Use std:: for standard string class
            std::string getName() const;
            std::string getAlias() const;
    //more stuff
    };
    
    typedef std::string (Connection::*Con_Func)() const;
    
    template<Con_Func _Name>
    class Foo{
        Connection m_Connect;
    public:
        // Constructors don't have return values
        Foo(){
             // Correct syntax for function call through pointer to member
             std::cout << (m_Connect.*_Name)();
        }
    };
    
    typedef Foo<&Connection::getName> NamedFoo;
    typedef Foo<&Connection::getAlias> AliasFoo;