c++ - 使用不完整类型显式实例化函数模板

标签 c++ templates

以下内容:

template< typename >
struct S;

template< typename T >
S< T >& f (S< T >& s) {
    const typename S< T >::nested ignore;
    return s;
}

template S< char >& f (S< char >&);

template< typename >
struct S {
    struct nested { };
};

使用 gcc 编译,但不使用 clang:

$ clang -c /tmp/t.cpp
/tmp/t.cpp:6:20: error: implicit instantiation of undefined template 'S<char>'
    const typename S< T >::nested ignore;
                   ^
/tmp/t.cpp:10:21: note: in instantiation of function template specialization 'f<char>' requested here
template S< char >& f (S< char >&);
                    ^
/tmp/t.cpp:2:8: note: template is declared here
struct S;
       ^
1 error generated.

我相信 clang 是正确的,因为在实例化时,函数 f 指的是 S 的不完整定义。OTOH,S 的后期特化可能会提供正确的定义,使相关的“嵌套”格式正确.有什么意见吗?

最佳答案

两个编译器都是正确的。

[温度点]/p6, 8:

6 An explicit instantiation definition is an instantiation point for the specialization or specializations specified by the explicit instantiation.

8 A specialization for a function template [...] may have multiple points of instantiations within a translation unit, and in addition to the points of instantiation described above, for any such specialization that has a point of instantiation within the translation unit, the end of the translation unit is also considered a point of instantiation. [...] If two different points of instantiation give a template specialization different meanings according to the one definition rule (3.2), the program is ill-formed, no diagnostic required.

f<char>有两个实例化点:在显式实例化定义和 TU 的末尾。因为这两个实例化点会产生不同的含义(因为查找 S<T>::nested 会产生不同的结果),所以该程序是格式错误的 NDR。

关于c++ - 使用不完整类型显式实例化函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32555618/

相关文章:

c++ - 如何让这个模板类编译?

c++ - 是否有可能/希望创建不可复制的共享指针模拟(以启用 weak_ptr 跟踪/借用类型语义)?

c++ - 构建垂直的 IE 资源管理器栏(带​​对象)(如收藏夹面板)

c++ - 测量 C++ OpenMP 代码中的执行时间

c# - 'ShowSUM' : __declspec(dllexport) cannot be applied to a function with the __clrcall calling convention

c++ - 使用带有转发引用的 std::forward

c++ - SetWindowsHookEx 成功但从未调用回调函数

C++ 为所有 std::sets 编写通用函数

c++ - 限制模板功能

javascript - 单击事件时使用 jQuery 在 Smarty 输入字段中动态主机名