2012-07-17 75 views
1

像这样使用模板可能吗?班级成员的模板参数

template<class T, int T::M> 
int getValue (T const & obj) { 
    return obj.M; 
} 

class NotPlainOldDataType { 
public: 
    ~NotPlainOldDataType() {} 
    int x; 
} 

int main (int argc, char ** argv) { 
    typedef NotPlainOldDataType NPOD; 
    NPOD obj; 

    int x = getValue<NPOD, NPOD::x>(obj); 

    return x; 
} 

我已经知道如何做到这一点使用宏

#define GET_VALUE(obj, mem) obj.mem 

class NotPlainOldDataType { 
public: 
    ~NotPlainOldDataType() {} 
    int x; 
} 

int main (int argc, char ** argv) { 
    NotPlainOldDataType obj; 

    int x = GET_VALUE(obj, x); 

    return x; 
} 

回答

7

如果我正确理解你的意图,那么下面应该工作:

#include <iostream> 

template<typename T, int (T::*M)> 
int getValue(T const& obj) 
{ 
    return obj.*M; 
} 

class NotPlainOldDataType 
{ 
public: 
    explicit NotPlainOldDataType(int xx) : x(xx) { } 
    ~NotPlainOldDataType() { } 
    int x; 
}; 

int main() 
{ 
    typedef NotPlainOldDataType NPOD; 

    NPOD obj(3); 
    std::cout << getValue<NPOD, &NPOD::x>(obj) << '\n'; 
} 

Online demo