gpt4 book ai didi

c++ - 下面的程序应该按照标准编译吗?

转载 作者:可可西里 更新时间:2023-11-01 16:24:04 25 4
gpt4 key购买 nike

在我发现 MSVC 和 GCC(可能也是 clang)在编译和链接相同代码时不一致之后,我开始好奇这个程序是否真的编译和链接,因此它是 MSVC 中的错误(它报告链接器错误) 或者我应该以不同的方式写它。该程序由 3 个文件组成:

C.h

template <typename T>
struct A
{
void func() {};
};

template <>
void A<int>::func ();

A.cpp:

#include "C.h"
int main()
{
A<int> x;
x.func();
}

B.cpp:

#include "C.h"
template <>
void A<int>::func()
{
}

MSVC 产生的链接器错误是:

A.obj : error LNK2019: unresolved external symbol "public: void __thiscall A::func(void)"

所以基本上它决定不创建放置在 B.cpp 中的定义之外的符号。让我强烈怀疑它是一个错误的是,将 func 的非特化定义移出结构定义,甚至将其放在特化声明之上会使程序链接成功,但我想确定。

所以我的问题是 - 该程序是否应该由符合标准的编译器/链接器编译和链接而没有错误?

最佳答案

来自标准:

© ISO/IEC N4527 14.6.4.1 Point of instantiation [temp.point] 1 For a function template specialization, a member function template specialization, or a specialization for a member function or static data member of a class template, if the specialization is implicitly instantiated because it is referenced from within another template specialization and the context from which it is referenced depends on a template parameter, the point of instantiation of the specialization is the point of instantiation of the enclosing specialization. Otherwise, the point of instantiation for such a specialization immediately follows the namespace scope declaration or definition that refers to the specialization.

在这种情况下,我认为这意味着在 C.h 发生“范围声明”的地方。如果是这种情况,那么您的代码应该与符合标准的工具链链接。我可能误解了这个……

关于c++ - 下面的程序应该按照标准编译吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422636/

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