提供 class 模板如何解决无效的 constexpr 依赖关系? C++
How does providing a class a template solve invalid constexpr dependencies? C++
类 在另一个 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.
类 在另一个 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.