2010-05-17 78 views
1

是否可以使用成员函数指针与模板元编程?如:带成员函数指针的模板元编程?

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

上的指针到非静态成员作为模板参数的主题退房this discussion。它看起来像VC++实施有问题。

+0

啊哈! VC++实现的问题!去搞清楚。 – wheaties 2010-05-17 18:32:30

2

如果你问,可以指向成员的指针作为模板参数,然后是的,他们可以。尽管你的代码有很多错误。这是,我想,你可能是什么意思:

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

你说得对。坚持下去,你拥有的就是我的代码。我最初写了'void Bar()',但是回溯到构造函数。 – wheaties 2010-05-17 18:33:09