代码之家  ›  专栏  ›  技术社区  ›  gast128

条件constexpr函数

  •  0
  • gast128  · 技术社区  · 6 年前

    template <typename T>
    struct Wrapper
    {
        friend constexpr bool operator==(const Wrapper& crLhs, const Wrapper& crRhs) noexcept
        {
            return crLhs.m_t == crRhs.m_t;
        }
    
        T m_t = {};
    };
    

    使用Visual Studio 2017 15.9.20时,这会给出“error C3615:constexpr function”operator==“在为std::string实例化时无法生成常量表达式”。信息是正确的,但我是 在constexpr上下文中实例化它。

    void f()
    {
       bool b;
    
       Wrapper<int>  a;
    
       b = a == a; //ok
    
       Wrapper<std::string> c;
    
       b = c == c;  //C3615, but not using constexpr context
    }
    

    0 回复  |  直到 6 年前
        1
  •  3
  •   Alecto Irene Perez    6 年前

    你的密码没问题。这是旧版本MSVC中的一个错误。

    此错误已在MSVC 19.22版中修复,并且编译时没有错误。在这里我们可以看到两个编译器版本的并排: https://godbolt.org/z/79kXFm

    GCC和Clang从来没有过这个bug。

    这个错误只出现在MSVC中,即使是非常旧的GCC和Clang版本也会编译代码而不会给您一个错误。

    如果可能的话,您应该转移到较新版本的Visual Studio。这是升级编译器的最简单的选项,如果您迁移到新版本,编译器将收到错误修复和升级。如果这不是一个选择,我会谷歌不同的方式升级只是编译器本身。这个 might be helpful .