c++ - "template"关键字之前的 "class"关键字在做什么?

标签 c++ templates

只是一些代码示例[不是现实生活中的例子]

// at file scope

template <typename T, typename U>
struct demo{};  
template class demo<int, int>; // is the template keyword optional here?

第 3 行中的模板关键字是可选的吗?我以前没有(经常)看到模板关键字的这种用法。标准的哪一部分说允许这样做?

编辑

我认为 g++ 有一个错误。

template <typename T, typename U>
struct demo{};  
class demo<int, int>; // template keyword omitted

在 g++ (4.5.1) 上编译而在 Comeau 上失败

"ComeauTest.c", line 5: error: specializing class "demo<int, int>" without
          "template<>" syntax is nonstandard
      class demo<int, int>; 

最佳答案

这是一个显式实例化

通常,当您使用模板时,编译器会根据您的需要生成您需要的内容。然而,要在静态或动态库中提供类模板的基本特化,您需要一次性生成所有成员,以确保将它们交付给用户。

例如,大多数 C++ 标准库的实现明确特化了 std::ostream<char,char_traits<char> > ,因为否则应用程序最终会包含对 cout 的各种操作的重复拷贝.

此语法与显式实例化相同。 C++03 §14.7.2/2:

The syntax for explicit instantiation is:

explicit-instantiation:

template declaration

编辑:

看起来您偶然发现了用于专门化 的过时语法,而不是显式实例化类模板。 Comeau 警告您,它将 template-id 声明作为显式特化的前向声明。想必 GCC 也在做同样的事情。在这种情况下,您不太可能获得显式实例化。此外,在定义之前使用显式模板特化是未定义的行为。 (从根本上说,隐式特化会导致违反单一定义规则。)

注意 GCC 也支持 extern模板实例化:

extern template declaration

在外部函数实例化的情况下,如果 template 我不会感到惊讶是可选的。但是,我不会惊讶地发现它是必需的,也不会忽略它。

关于c++ - "template"关键字之前的 "class"关键字在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769140/

相关文章:

c++ - 从 'int' 到 'const char*' [-fpermissive] 的无效转换

c++ - 未定义的 C/C++ 符号作为运算符

c++ - QToolButton 和颜色

c++ - 涉及 iostream 和 wstring 的奇怪 C++ 行为

c++ - OpenCV C++ : How to find all the circles in an image

c++ - 非常量指针类型的参数不调用带有常量指针模板类型参数的函数

c++ - 如何从模板生成具有 const 或非常量成员函数的类?

c++ - 如何使类模板的子类成为类模板?

c++ - 模板类或函数可以将不同的数据类型作为参数吗?

C++ 模板类作为函数的参数