1

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah ha! Problems with VC++ implementation! Go figure.
2

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;

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.