2010-06-11 37 views
2

我有一个类C++模板特

template <typename T> 

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

我想专门下INT。

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

我想要保留int的默认打印方法,只是改变常量。 对于某些专业,我想保留K = 1并更改打印方法,因为 不是< <运算符。

我该怎么做?

回答

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; 
+0

如果一切都在被多次包括头文件?这不会导致链接器中出现多重定义错误吗? – user231536 2010-06-14 17:31:40

+0

@ user231536:你可以在头文件中声明'template <> const int C :: K;'以清楚地说明这种情况下有一个专门化, 然后把'... = 2; '.cpp文件中只有一个值的定义。 – sth 2010-06-14 20:48:16

3

在C++ 0x中:

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