Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specialize a static member of a template class on a templated type?

Tags:

c++

Say I have the following class:

template<class T>
struct A
{
    static int value;
};

template<class T>
int A<T>::value = 0;

I can specialize A::value on a concrete type without problems:

struct B
{
};

template<>
int A<B>::value = 1;

I'd like to specialize A::value on a template type, I tried the following:

template<class T>
struct C
{
};

// error: template definition of non-template 'int A<C<T> >::value'
template<>
template<class T>
int A<C<T> >::value = 2;

Is there any way to do this or is it only possible to specialize A::value on non-template types?

like image 375
Greg Rogers Avatar asked Oct 16 '10 16:10

Greg Rogers


2 Answers

Instead of introducing a whole explicit specialization, you could just specialize the initialization

template<class T>
struct Value {
  static int const value = 0;
};

template<class T>
struct Value< C<T> > {
  static int const value = 2;
};

template<class T>
int A<T>::value = Value<T>::value;
like image 127
Johannes Schaub - litb Avatar answered Sep 21 '22 12:09

Johannes Schaub - litb


You can use partial specialization of A via C:

#include <iostream>

using namespace std;

template<class T>
struct A
{
    static int value;
};

template<class T>
int A<T>::value = 0;

//(1) define the C template class first:
template<class T>
struct C
{
};

//(2) then define the partial specialization of A, in terms of C:
template<typename T>
struct A<C<T> > 
{
    static int value;
};

template<typename T>
int A<C<T> >::value = 2;

int main(void)
{
    cout<<A<C<int> >::value<<endl;

    cout<<"ok!"<<endl;
    return 0;
}
like image 42
blue scorpion Avatar answered Sep 19 '22 12:09

blue scorpion