gpt4 book ai didi

c++ - 非成员函数模板什么时候有内部链接?

转载 作者:太空狗 更新时间:2023-10-29 20:56:10 29 4
gpt4 key购买 nike

C++11 草案,14.0.4:

A non-member function template can have internal linkage; any other template name shall have external linkage.

此查询是分离模板声明和定义的结果。例如,我们可以在头文件中写入如下内容。

template <typename T>
bool operator==(T const & l, T const & r);

在一个注定要成为一个翻译单元的单一源文件中,我们编写了定义。我们还在同一个翻译单元中为 foo 类型隐式或显式实例化它。

template <typename T>
bool operator==(T const & l, T const & r)
{
return extract(l) == extract(r); // extract is uninteresting
}

在只能从 header 中看到定义的第二个翻译单元中,我们尝试使用 foo{} == foo{},即调用 operator= = 在别处实例化。

目前,这个“有效”。链接器如我所愿地修补了两个翻译单元。

但是,如果函数模板有内部链接,链接可能会失败。例如,我们可以通过在匿名命名空间中实例化来强制执行此操作。

规范中的“can”是否表示源代码控制链接(例如通过 namespace {})或者是否允许编译器选择实例化是否具有内部或外部链接?

我不相信这里有任何未定义的行为,但我正在努力说服自己选择的链接不是实现细节。如果符号已在至少一个 TU 中实例化,表明它将是外部的,我是否可以依赖其他翻译单元可见的符号?

编辑:DR1603 (感谢 Eugene Zavidovsky!)包含一个建议,以完全删除上面引用的句子,以及链接规则的一般合理化。

最佳答案

Does the "can" in the spec indicate that the source code controls the linkage (e.g. by namespace {}) or that the compiler is permitted to choose whether the instantiation will have internal or external linkage?

这是控制链接的代码。从函数模板生成的函数具有外部链接,除非它是一个static 函数模板或模板在未命名的命名空间中(C++11 起)。

换句话说,必须明确要求内部链接。

关于c++ - 非成员函数模板什么时候有内部链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34201090/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com