c++ - `class template Example<int>;` 语句对 C++11 意味着什么?

标签 c++ c++11 templates

有人提到我 "Explicit Template Instantiation"cplusplus.com ,它给出了以下示例:

template <typename T> class Example
{
public:
    Example( T test )
    {
        _data = test;
    }
    void setTest(T test)
    {
        _data = T;
    }
private:
    T _data;
};

class template Example<int>;
class template Example<float>;
class template Example<double>;

除了在我看来是一个遗漏错误之外,试图将类型分配给成员变量 -- _data = T而不是我认为应该是 _data = test -- 我不明白的是最后 3 行究竟声明或指示编译器做什么?

我知道什么是模板,用它们构建了程序,并且大致了解它们的实例化和特化。我对后两者的理解确实可能存在一些漏洞,但我通常使用例如指示显式模板实例化template class Example<int>;形式,而不是代码段中显示的形式。

我尝试使用 g++ -std=c++11 -pedantic 编译代码片段它编译得很好,没有警告(我先纠正了上面的 _date = T 错误)。

这是在我评论 an answer to a related question 之后出现的而且我仍然不确定代码段中的最后 3 行是模板特化还是实例化。

我还尝试在 C++11 draft published by ISO 中找到相关的语法生成规则(在 template 之后允许 class )但空手而归。

最佳答案

我们从下面的神栓可以看出example根据 clang 和 MSVC 并查看有关显式实例化部分的标准草案部分,这是格式错误的 [temp.explicit]我看不出有任何理由让 gcc 接受它。

鉴于主题,我认为文章“可能”的意思是:

template class Example<int>;
template class Example<float>;
template class Example<double>;

那确实is well-formed with gcc/clang/MSVC .

看起来在 C++11 之前允许使用此语法,请参阅 defect report 1707: template in elaborated-type-specifier without nested-name-specifier (强调我的):

The grammar for elaborated-type-specifier in 10.1.7.3 [dcl.type.elab] reads, in part,

elaborated-type-specifier:
    class-key nested-name-specifieropt templateopt simple-template-id

允许使用模板关键字而不需要 嵌套名称说明符,例如结构模板 S。 这是 与 template 关键字的其他用法不一致。有可能 最好将生产分成两部分,只允许关键字 在嵌套名称说明符之后,

....

所以这更有意义with this comment -ansi 会导致警告。

其他answerer filed two bug reports .

cppreference has a good dicssuion of Explicit instantiation还有这个问题 Explicit instantiation - when is it used?详细解释了为什么这是有用的。

另请注意,我们可以看到这个 Meta post: Links being changed to cppreference.com该网站已知有不正确的信息,一般来说,社区更喜欢 cppreference作为可靠的 C++ 引用。

关于c++ - `class template Example<int>;` 语句对 C++11 意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53030882/

相关文章:

c++ - 如何使用 C++ 从 .exe 读取/写入 asm 寄存器?

c++ - 链表深拷贝构造函数

c++ - 赋值与初始化期间的类型安全

c++ - Linux 和 Windows c++ 上的低级文件操作处理

c++ - HIP-Clang 内联装配

c++ - 如何在 MSVC 中使用使用 MingW 编译的库?

c++ - auto 关键字的声明点

c++ - 在显式初始化期间尝试创建函数拷贝时出错

c++11 - C++ 11编译失败, undefined reference ,另一个类内部的显式模板类实例化

c++ - 接受 char* 的模板化函数