[英]Link error with MSVC but not with g++ with constexpr
Consider the following code: 请考虑以下代码:
#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;
}
It works fine with g++ -std=c++1z Main.cpp
but in Visual Studio with MSVC set with c++17 support it gives 它适用于
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
Is this a bug in MSVC? 这是MSVC中的错误吗?
Is this a bug in MSVC?
这是MSVC中的错误吗?
No, FactoryTag::shape
is odr-used here, so it needs a definition (you're copy-constructing it, which goes through the implicitly generated copy constructor, which requires you to bind a reference). 不,
FactoryTag::shape
在这里使用的是odr ,所以它需要一个定义(你是复制构造它,它通过隐式生成的复制构造函数,它要求你绑定一个引用)。 Nor is this a bug in gcc either, arguably, since there is no diagnostic required if a definition is missing. 也许这也不是gcc中的错误,因为如果缺少定义则不需要诊断 。
The solution is to add a definition. 解决方案是添加定义。 The old way would be:
旧的方式是:
struct FactoryTag { ... };
Shape FactoryTag::shape{}; // somewhere in a source file
The new way would be: 新的方式是:
struct FactoryTag {
struct Shape {} static constexpr shape {}; // implicitly inline in C++17
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.