代码之家  ›  专栏  ›  技术社区  ›  stefanB

是否可以访问专用模板类中非类型模板参数的值?

  •  10
  • stefanB  · 技术社区  · 15 年前

    是否可以访问专用模板类中非类型模板参数的值?

    如果我有专门化的模板类:

       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;
           ...
       }
    
    3 回复  |  直到 15 年前
        1
  •  16
  •   stefanB    15 年前

    这种问题可以通过一组单独的“特征”结构来解决。

    // 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; 
        }   
    };
    
        2
  •  1
  •   Dave Gamble    15 年前

    对你的问题没有真正的答案,但你可以列举出来,即:

    enum{
     specialisationMajor=4,
     specialisationMinor=0
    };
    
    template <> struct A<specialisationMajor,specialisationMinor> {
        static const int major = specialisationMajor;
        static const int minor = specialisationMinor;
        ...
    }
    
        3
  •  0
  •   Aliaksei Sanko    6 年前

    不是你的问题的真正答案,但下面的想法曾经帮助过我:

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