【发布时间】:2020-11-19 18:20:50
【问题描述】:
[dcl.spec.auto]/14 声明 [强调 我的]:
显式实例化声明不会导致使用占位符类型声明的实体实例化,但它也不会阻止根据需要实例化该实体以确定其类型。 [ 示例:
template <typename T> auto f(T t) { return t; } extern template auto f(int); // does not instantiate f<int> int (*p)(int) = f; // instantiates f<int> to determine its return type, but an explicit // instantiation definition is still required somewhere in the program— 结束示例 ]
和[temp.explicit]/11 表示[强调我的]:
一个实体,它是显式实例化声明的主题,并且也以会导致隐式实例化的方式使用在翻译单元中应该是程序中某处显式实例化定义的主题;否则程序是不正确的,不需要诊断。
现在,考虑以下程序:
template <class T>
struct Foo {
static const auto& foo() { static T t; return t; }
};
// explicit instantiation declarations
extern template const auto& Foo<void>::foo();
extern template const auto& Foo<int>::foo();
int main() {}
这是格式良好的; [temp.explicit]/11 不适用于类模板特化实体 Foo<void>::foo() 和 Foo<int>::foo() 的成员函数,其使用方式会导致隐式实例化,根据 [dcl.spec.auto]/14(1) .
现在,考虑我们是否在类模板Foo 的朋友声明中定义了一个朋友函数:
template <class T>
struct Foo {
static const auto& foo() { static T t; return t; }
friend void bar() { }
};
void bar();
如果Foo 的任何一个以上特化在同一个翻译单元中被实例化,[basic.def.odr]/1 将被违反:
任何翻译单元都不得包含一个以上的任何变量、函数、类类型、枚举类型或模板的定义。
作为朋友bar() 将被重新定义(2) 用于实例化的每个特化。
根据上面的论点,两个成员函数(类模板)特化的显式实例化声明不应导致相关类模板的任何实例化(根据[dcl.spec.auto]/14),这意味着以下程序也应该有争议格式正确:
template <class T>
struct Foo {
static const auto& foo() { static T t; return t; }
friend void bar() { }
};
void bar();
extern template const auto& Foo<void>::foo();
extern template const auto& Foo<int>::foo();
int main() {}
但是,Clang (10.0.0) 和 GCC (10.1.0) 都拒绝程序(C++14、C++17、C++2a),并出现“重新定义 void bar()”错误:
叮当
错误:
bar的重新定义注意:在此处请求的模板类
Foo<int>的实例化中:extern template const auto& Foo<int>::foo();GCC
在
struct Foo<int>的实例化中:错误:
void bar()的重新定义
但我从未要求(或者说,以某种方式使用这些特化)Foo<int> 或 Foo<void> 特化(是)被实例化。
因此问题:
- 上面的程序(和朋友一起)是否格式正确,或者编译器是否正确实例化类模板特化并随后拒绝该程序?
(1) 请注意,即使 foo() 没有使用占位符类型声明,同样的问题(和编译器行为)也适用,但是我们将无法依赖 [dcl.spec.auto]/14 的明确性,但我们可能不需要。
(2) 由于在他们的朋友声明中定义的朋友是内联的,我们实际上可以在不同的翻译单元中实例化不同的特化并且仍然尊重 ODR,但这与本次讨论无关。
【问题讨论】:
标签: c++ templates language-lawyer instantiation friend