c++ - 为类提供模板如何解决无效的 constexpr 依赖关系? C++

标签 c++ visual-studio templates c++17 constexpr

类在另一个 constexpr 上下文中调用它们的 constexpr 成员函数时似乎有问题。例如,在我提出的这段代码中 in an earlier question可以看到这种行为:

struct Foo {
    constexpr static bool TRUE() {
        return true;
    }
    static_assert(Foo::TRUE(), ""); //ERROR
};

作为 static_assert取决于 Foo::TRUE()编译失败,因为 Foo::TRUE()在这种情况下尚未完全解决。


那么如何将单个模板添加到 Foo解决整个问题?:

template<int x>
struct Foo {
    constexpr static bool TRUE() {
        return true;
    }
    static_assert(Foo::TRUE(), ""); //compiles fine
};

在所有这些见解之后,这里的代码不应该编译 - 但它可以编译。这似乎没有意义,因为与非模板版本没有任何区别。

此外,TRUE() 的数量应该总是相等的-功能和static_assert -有电话Foo<>类,所以编译时应该会出现同样的依赖问题。


我正在使用 Visual Studio 17 社区版本 15.9.0 - 感谢您的帮助!

最佳答案

这是 CWG 1626 :

The Standard should make clear that a constexpr member function cannot be used in a constant expression until its class is complete. For example:

template<typename T> struct C {
  template<typename T2> static constexpr bool _S_chk() {
    return false;
  }
  static const bool __value = _S_chk<int>();
}; 

C<double> c;

Current implementations accept this, although they reject the corresponding non-template case:

struct C {
  static constexpr bool _S_chk() { return false; }
  static const bool __value = _S_chk();
};

C c; 

Presumably the template case should be handled consistently with the non-template case.

关于c++ - 为类提供模板如何解决无效的 constexpr 依赖关系? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53634141/

相关文章:

c++ - 将 AVPackets 混合到 mp4 文件中

c++ - 在代码注释中接受字符串结果

c++ - 为什么 C++ 允许永远不能使用的默认模板参数?

c++ - `struct ap_conf_vector_t` 的定义在哪里?

c++ - 使用 fwrite() 和 fread() 进行二进制输入/输出

c# - 如何在 Visual Studio 2015 中使用 Webbrowser Edge 而不是默认 Web 浏览器

c - 程序在 Visual C++ 中突然终止

C++11 函数模板特化为类方法(如果存在)

python - 在 flask 中渲染模板后更新Jinja元素

c++ - 在 Windows 上与 taglib 链接错误