C++ C++;专门化模板类以获取其他模板参数
是否可以专门化模板类以获取其他模板参数 例如:C++ C++;专门化模板类以获取其他模板参数,c++,templates,specialization,C++,Templates,Specialization,是否可以专门化模板类以获取其他模板参数 例如: template <typename T> struct X { void foo() { cerr << "Generic" << endl;} }; template <> template <bool b> struct X<int> { void foo() { cerr << "Specialization" << endl;} }
template <typename T>
struct X {
void foo() { cerr << "Generic" << endl;}
};
template <>
template <bool b>
struct X<int> {
void foo() { cerr << "Specialization" << endl;}
};
模板
结构X{
void foo(){cerr您可以更改主模板以接受代理特性类:
template <typename T>
struct Foo
{
typedef typename T::type type;
// work with "type"
void static print() { std::cout << T::message << std::endl; }
}
模板
结构Foo
{
typedef typename T::type类型;
//与“类型”一起工作
void static print(){std::你听说过部分模板专门化吗?“如果必须的话,有没有办法让用户不必为它指定任何值?”是的——默认模板参数。例如,template
。正如@ildjarn所说,您可以——但我要提醒的是,在大多数情况下,最好使用bool以外的类型。mytempla
vs.myempla
通常比mytempla
vs.mytempla
更有意义。您不必更改主模板那就做一个专门化,接受traits
。
template <typename T>
struct traits
{
typedef T type;
static const char * const message = "Generic";
};
template <>
struct traits<int>
{
typedef int type;
static const char * const message = "Specialized";
};