user231536
user231536

Reputation: 2711

C++ template specialization

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?

Upvotes: 2

Views: 588

Answers (2)

rafak
rafak

Reputation: 5551

In C++0x:

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

Upvotes: 3

sth
sth

Reputation: 229563

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;

Upvotes: 9

Related Questions