Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top