views:

105

answers:

2

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.)

+2  A: 

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 funtion call through pointer to member
         std::cout << (m_Connect.*_Name)();
    }
};

typedef Foo<&Connection::getName> NamedFoo;
typedef Foo<&Connection::getAlias> AliasFoo;
Charles Bailey
You're right. Hold on, what you have is what I have in my code. I had originally writte `void Bar()` but backtracked to a constructor.
wheaties
+1  A: 

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.

luke
Ah ha! Problems with VC++ implementation! Go figure.
wheaties