views:

114

answers:

2

I have a class

template <typename T>

    class C
    {
     static const int K=1;
     static ostream& print(ostream& os, const T& t) { return os << t;}
    };

I would like to specialize C for int.

 //specialization for int
 template <>
 C<int>{
 static const int K=2;
}

I want the default print method that works for int to remain and just change the constant. For some specializations, I want to keep K=1 and change the print method because there is no << operator.

How do I do this?

+9  A: 

You could do it like this:

template <typename T>
class C {
   static const int K;
   static ostream& print(ostream& os, const T& t) { return os << t;}
};

// general case
template <typename T>
const int C<T>::K = 1;

// specialization
template <>
const int C<int>::K = 2;
sth
@sth: What if all was in a header file that was included multiple times? Wouldn't that lead to a multiple definition error in the linker?
@user231536: You can put the declaration `template<>const int C<int>::K;` in the header to make it clear that there is a specialization for that case,and then put `... = 2;` in the .cpp file to have only one definition of the value.
sth
+3  A: 

In C++0x:

static const int K = std::is_same<T, int>::value ? 2 : 1;

rafak