繁体   English   中英

C ++模板专业化

[英]C++ template specialization

我上课了

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并更改print方法,因为没有<<运算符。

我该怎么做呢?

你可以这样做:

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;

在C ++ 0x中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM