c++ - 与 MSVC 的链接错误,但与带有 constexpr 的 g++ 的链接错误

标签 c++ gcc visual-c++ c++17

考虑以下代码:

#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::shapeodr-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/

相关文章:

c++ - 有哪些简单的方法可以用 COM 接口(interface)包装基于 C++ 的对象模型

C++:#include 文件搜索?

c++ - 如果我递减 `std::size_t(0)` 是否保证等于 `std::size_t(-1)`?

c++ - 获取 C++ double 函数以在满足特定条件时报告消息而不是返回数字

c - syscall 是 x86_64 上的指令吗?

在 OS X El Capitan 上使用 libssl 编译 C 程序?

c++ -/Ox 和/O2 编译器选项有什么区别?

c++ - 为什么 `is_constructible<function<int(int)>, int(*)(int,int)>::value`在VC2015RC下为true

c++ - 如何在cpp中使用QThread使用一个对象运行同一类的两个线程?

c - C语言中定义的 'int'和 'char'类型在哪里?