views:

230

answers:

2

Is it possible to access values of non-type template parameters in specialized template class?

If I have template class with specialization:

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

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

I know it the above case it is simple to hardcode values 4 and 0 instead of using variables but what I have a larger class that I'm specializing and I would like to be able to access the values.

Is it possible in A<4,0> to access major and minor values (4 and 0)? Or do I have to assign them on template instantiation as constants:

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

Not really an answer to your question, but you could enumerate them, viz:

enum{
 specialisationMajor=4,
 specialisationMinor=0
};

template <> struct A<specialisationMajor,specialisationMinor> {
    static const int major = specialisationMajor;
    static const int minor = specialisationMinor;
    ...
}
Dave Gamble
I'm trying to avoid defining another set of variables ... that was the beauty of having those template parameters, I dont' usually want to access the values ... but nevermind, but thanks
stefanB
+8  A: 

This kind of problem can be solved by having a separate set of "Traits" structs.

// 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; 
    }   
};
Andrew Shepherd
+1 nice, thanks
stefanB