wheaties
wheaties

Reputation: 35970

Template meta-programming with member function pointers?

Is it possible to use member function pointers with template meta-programming? Such as:

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;

Granted, this is rather contrived but is it possible? (yes, there are probably much better ways but humor me.)

Upvotes: 1

Views: 979

Answers (2)

CB Bailey
CB Bailey

Reputation: 791551

If you are asking, can pointers to members be used as template parameters, then yes they can. There are a number of errors in your code though. This is, I think, what you might mean:

// 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;

Upvotes: 2

luke
luke

Reputation: 37443

Check out this discussion on the subject of pointers-to-nonstatic-members as template parameters. It looks like there are issues with the VC++ implementation.

Upvotes: 2

Related Questions