类在另一个 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/