2012-07-17 5 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