Можно ли получить доступ к значениям нетиповых параметров шаблона в специализированном шаблонном классе? - PullRequest
10 голосов
/ 22 июля 2009

Возможно ли получить доступ к значениям нетиповых параметров шаблона в специализированном классе шаблона?

Если у меня есть шаблон класса со специализацией:

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

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

Я знаю, что в приведенном выше случае просто жестко кодировать значения 4 и 0 вместо использования переменных, но у меня есть класс, который я специализирую, и я хотел бы иметь возможность доступа к значениям.

Возможно ли в A <4,0> получить доступ к значениям major и minor (4 и 0)? Или я должен назначить их при создании шаблона как константы:

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

Ответы [ 3 ]

16 голосов
/ 22 июля 2009

Эту проблему можно решить с помощью отдельного набора структур «Черты».

// 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; 
    }   
};
1 голос
/ 22 июля 2009

Не совсем ответ на ваш вопрос, но вы можете перечислить их, а именно:

enum{
 specialisationMajor=4,
 specialisationMinor=0
};

template <> struct A<specialisationMajor,specialisationMinor> {
    static const int major = specialisationMajor;
    static const int minor = specialisationMinor;
    ...
}
0 голосов
/ 08 октября 2018

Не совсем ответ на ваш вопрос, но однажды мне помогла идея ниже:

#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();
}
...