以下内容:
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/