考虑以下代码:
#include <iostream>
struct FactoryTag
{
static struct Shape {} shape;
static struct Color {} color;
};
template <typename TFactory>
int factoryProducer(TFactory tag)
{
if constexpr (std::is_same<TFactory, FactoryTag::Shape>::value)
return 12;
else if constexpr (std::is_same<TFactory, FactoryTag::Color>::value)
return 1337;
}
int main()
{
std::cout << factoryProducer(FactoryTag::shape) << std::endl;
return 0;
}
它适用于 g++ -std=c++1z Main.cpp
但在 Visual Studio 中,MSVC 设置为 c++17 支持,它给出了
Error LNK2001 unresolved external symbol "public: static struct FactoryTag::Shape FactoryTag::shape" (?shape@FactoryTag@@2UShape@1@A) StaticTest C:\Users\danielj\source\repos\StaticTest\StaticTest\StaticTest.obj 1
这是 MSVC 中的错误吗?
最佳答案
Is this a bug in MSVC?
不,FactoryTag::shape
是 odr-used 在这里,所以它需要一个定义(你正在复制构造它,它通过隐式生成的拷贝构造函数,它需要你绑定(bind)一个引用)。这也不是 gcc 中的错误,可以说,因为有 no diagnostic required如果缺少定义。
解决方案是添加一个定义。旧方法是:
struct FactoryTag { ... };
Shape FactoryTag::shape{}; // somewhere in a source file
新的方式是:
struct FactoryTag {
struct Shape {} static constexpr shape {}; // implicitly inline in C++17
};
关于c++ - 与 MSVC 的链接错误,但与带有 constexpr 的 g++ 的链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52501192/