本文介绍了使用不完整类型显式实例化函数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容:

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:

compiles with gcc, but not with 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 的后期特化可能会提供正确的定义,使依赖的嵌套"格式良好.有什么意见吗?

I believe clang to be right in that, at the point of instantiation, the function f refers an incomplete definition of S. OTOH, a later specialization of S might provide the correct definition that makes the dependent 'nested' well-formed. Any opinions?

推荐答案

两个编译器都是正确的.

Both compilers are correct.

[温度点]/p6, 8:

[temp.point]/p6, 8:

6 显式实例化定义是一个实例化点显式指定的专业化或专业化实例化.

8 函数模板的特化 [...]在一个翻译单元中有多个实例化点,以及除了上述实例化点之外,对于任何这种特化在内部有一个实例化点翻译单元,翻译单元的结尾也被认为是一个实例化点.[...] 如果两个不同的实例化点根据一个模板特化赋予不同的含义定义规则(3.2),程序格式错误,没有诊断需要.

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 有两个实例化点:在显式实例化定义处,以及在 TU 的末尾.因为这两个实例化点会导致不同的含义(因为查找 S<T>::nested 会产生不同的结果),该程序是格式错误的 NDR.

There are two points of instantiation for f<char>: at the explicit instantiation definition, and at the end of the TU. Because those two points of instantiation would result in different meanings (as lookup for S<T>::nested would yield different results), the program is ill-formed NDR.

这篇关于使用不完整类型显式实例化函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:15