c++ - C++中带有空尖括号的模板<>是什么意思?

标签 c++ templates

template<>
class A{
//some class data
};

这种代码我见过很多次了。 template<>有什么用在上面的代码中? 在哪些情况下我们需要强制使用它?

最佳答案

template<>告诉编译器后面跟着模板特化,特别是完全特化。通常情况下,class A必须看起来像这样:

template<class T>
class A{
  // general implementation
};

template<>
class A<int>{
  // special implementation for ints
};

现在,无论何时 A<int>使用,使用专用版本。您还可以使用它来专门化功能:

template<class T>
void foo(T t){
  // general
}

template<>
void foo<int>(int i){
  // for ints
}

// doesn't actually need the <int>
// as the specialization can be deduced from the parameter type
template<>
void foo(int i){
  // also valid
}

通常情况下,您不应该专门化函数,如 simple overloads are generally considered superior :

void foo(int i){
  // better
}

现在,为了夸大其词,以下是部分特化:

template<class T1, class T2>
class B{
};

template<class T1>
class B<T1, int>{
};

与完全特化的工作方式相同,只是只要第二个模板参数是 int,就会使用特化版本。 (例如,B<bool,int>B<YourType,int> 等)。

关于c++ - C++中带有空尖括号的模板<>是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6288812/

相关文章:

c++ - 为什么对于每个数组 a 和整数 j,a[j] 都等于 j[a]?

C# 泛型——基于类型特征的重载

c++ - 全局变量什么时候分配内存?

javascript - 从字符串模板获取通配符名称

c++ - 未找到使用表达式模板化的静态 constexpr 成员函数

c++ - 虚拟模板函数重载

javascript - 如何访问 JSCValue 对象的属性

javascript - 为什么使用 &lt;script&gt; 元素作为模板比其他元素更受欢迎?

c++ - 工业级n吨基类模板

c++ - 不依赖于系统时间的时间