2

我有一堂课

template <typename T>

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

我想将 C 专门用于 int。

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

我希望保留适用于 int 的默认打印方法,只需更改常量即可。对于某些专业,我想保持 K=1 并更改打印方法,因为没有 << 运算符。

我该怎么做呢?

4

2 回答 2

9

你可以这样做:

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;
于 2010-06-11T14:54:29.053 回答
3

在 C++0x 中:

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

于 2010-06-11T15:42:16.173 回答