【问题标题】:What is the meaning of template<> with empty angle brackets in C++?C ++中带有空尖括号的模板<>是什么意思?
【发布时间】:2011-06-09 06:18:51
【问题描述】:
template<>
class A{
//some class data
};

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

【问题讨论】:

  • 哦...在使用“模板”发布此内容之前,我尝试用谷歌搜索它,但效果不佳。感谢您提供正确的搜索关键字。但我认为 SO 更好回答它。

标签: c++ templates


【解决方案1】:

template&lt;&gt; 告诉编译器后面跟着模板特化,特别是完全特化。通常,class A 必须看起来像这样:

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

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

现在,无论何时使用A&lt;int&gt;,都会使用专用版本。您还可以使用它来专门化功能:

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&lt;bool,int&gt;B&lt;YourType,int&gt; 等),就会使用专业化版本。

【讨论】:

  • +1 好答案!也许您应该补充一点,这是一个完整的模板专业化。即使.. 使用一个模板参数,也不可能有部分特化。
  • 这对于定义类型特征也很有用。
  • @Xeo:我希望反对者发表评论,无论是否匿名(或至少是第一个)。
  • @Xeo:添加“为什么需要完整的模板专业化”可能是有意义的。我相信唯一有用的场景是模板元编程。有没有人有更多的见解?
  • @Jaywalker:你的意思是专门针对函数还是针对结构/类?
【解决方案2】:

template&lt;&gt; 介绍了模板的完全专业化。您的示例本身实际上是无效的;在它变得有用之前,您需要一个更详细的场景:

template <typename T>
class A
{
    // body for the general case
};

template <>
class A<bool>
{
    // body that only applies for T = bool
};

int main()
{
    // ...
    A<int>  ai; // uses the first class definition
    A<bool> ab; // uses the second class definition
    // ...
}

看起来很奇怪,因为它是更强大功能的特例,称为“部分特化”。

【讨论】:

  • 显式(非“总”)特化不是部分特化的特例。显式特化定义了一个由模板标识标识的类;部分特化定义了一个通过主模板访问的新模板。
  • 我更喜欢“total”这个词,因为它与“partial”(这是一个事物)相对立,而“explicit”与“implicit”(这不是一个事物)相对立。我知道这不是标准术语。从语法上讲,显式特化是部分特化的特例,即使以最符合标准的方式看待这两者,也会区分类和类模板。
【解决方案3】:

看起来不对。现在,你可能会写:

template<>
class A<foo> {
// some stuff
};

...这将是 foo 类型的 模板特化

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 1970-01-01
    • 2011-09-30
    • 2018-07-15
    • 1970-01-01
    • 2023-03-15
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多