특수 템플릿 클래스에서 유형이 아닌 템플릿 매개 변수의 값에 액세스 할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/1162401

문제

특수 템플릿 클래스에서 유형이 아닌 템플릿 매개 변수의 값에 액세스 할 수 있습니까?

전문화 된 템플릿 클래스가있는 경우 :

   template <int major, int minor> struct A {
       void f() { cout << major << endl; }
   }

   template <> struct A<4,0> {
       void f() { cout << ??? << endl; }
   }

위의 경우 변수를 사용하는 대신 하드 코드 값 4와 0은 간단하지만 전문화하는 클래스가 더 큰 클래스가있는 것이 값에 액세스 할 수 있기를 원합니다.

<4,0>에서 액세스 할 수 있습니까? major 그리고 minor 값 (4 및 0)? 아니면 템플릿 인스턴스화에 상수로 할당해야합니까?

   template <> struct A<4,0> {
       static const int major = 4;
       static const int minor = 0;
       ...
   }
도움이 되었습니까?

해결책

이런 종류의 문제는 별도의 "특성"구조 세트를 통해 해결할 수 있습니다.

// A default Traits class has no information
template<class T> struct Traits
{
};

// A convenient way to get the Traits of the type of a given value without
// having to explicitly write out the type
template<typename T> Traits<T> GetTraits(const T&)
{
    return Traits<T>();
}

template <int major, int minor> struct A 
{ 
    void f() 
    { 
        cout << major << endl; 
    }   
};

// Specialisation of the traits for any A<int, int>
template<int N1, int N2> struct Traits<A<N1, N2> >
{
    enum { major = N1, minor = N2 };
};

template <> struct A<4,0> 
{       
    void f() 
    { 
        cout << GetTraits(*this).major << endl; 
    }   
};

다른 팁

실제로 당신의 질문에 대한 답은 아니지만, 당신은 그것들을 열거 할 수 있습니다.

enum{
 specialisationMajor=4,
 specialisationMinor=0
};

template <> struct A<specialisationMajor,specialisationMinor> {
    static const int major = specialisationMajor;
    static const int minor = specialisationMinor;
    ...
}

실제로 귀하의 질문에 대한 답은 아니지만 아래 아이디어는 한 번 도움이되었습니다.

#include <iostream>

template <int major, int minor, int= major, int= minor> struct A {
    void f() { std::cout << major << '\n'; }
};

template <int major, int minor> struct A<major, minor, 4, 0> {
    void f() { std::cout << major << ':' << minor << '\n'; }
};

int main()
{
    A<3, 3>().f();
    A<4, 0>().f();
}

아니요, 특수 비 유형 템플릿 매개 변수에 액세스 할 수 없습니다. 그러나 다음은 f:

   template <int major, int minor>
   struct f_impl
   {
       void f() { cout << major << endl; }
   };

   template <int major, int minor>
   struct A : public f_impl<major, minor>
   {};

   template <> struct A<4,0> : public f_impl<4,0>
   {};

이 예에서는 하나가 너무 많이 얻지 못합니다. 4,0 두 번 (-그래서 당신은 그것을 두 번째로 쓸 수 있습니다. cout OP에서). 그러나 템플릿 매개 변수를 사용하여 더 많은 기능이 있으면 지불하기 시작합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top