我找不到与此相关的问题/答案。考虑一下:
// constexpr declares intent
template <typename T> inline constexpr const bool probe (T const &) noexcept { return false; }
template <typename T> inline constexpr const bool probe (T const *) noexcept { return true; }
template <typename T> inline constexpr const bool probe (T &&) noexcept = delete ;
template <typename T> inline constexpr const bool probe (T) noexcept = delete ;
众所周知并期望以下内容在编译时按预期工作:
constexpr inline const char * holla_ = "Hola!";
// OK
static_assert(probe(holla_));
// OK
static_assert(probe("string literal"));
还有这些:
inline const char buff[]{"ABCD"};
// OK -- although `buff` is not compile time array
static_assert(probe(buff));
constexpr inline int const * ip = nullptr ;
static_assert(probe(ip));
但这里是编译时不能做的区域:
// deliberately omitted constexpr
inline const char * wot_here_ = "Another literal";
// error: the value of 'wot_here_' is not usable in a
// constant expression
// note: 'wot_here_' was not declared 'constexpr'
// static_assert(probe(wot_here_));
我知道 wot_here_
是运行时变量。 probe()
仅使用参数类型进行声明和实现。我是否公开违反标准中的某些明显规则?或者巧妙地对抗一些微妙的。
我谨慎地希望有人能够“解决”这个问题?
最佳答案
I am really hoping someone can sort-of-a, "get around" this issue?
我看到的唯一“绕过”是 declate wot_her_
constexpr
.
如果你定义
inline const char * wot_here_ = "Another literal";
您有一个在运行时初始化的变量。
观察 const char *
是一个指向常量的变量指针 char
,所以不是一个常量值,因为您可以增加/减少它。
一个constexpr
函数也可以由运行时变量调用,因此您可以调用
probe( wot_here_)
但是probe()
在本例中,是在运行时执行的。
问题是 static_assert()
必然在编译时执行,所以
static_assert( probe( wot_here_) );
给出错误,因为编译器无法检查编译时运行时执行的内容。
我看到的唯一解决方案是定义 wot_here_
constexpr
,如holla_
之前,因此编译器可以在编译时执行 probe(wot_here_)
里面static_assert()
.
关于C++ 如何让 constexpr 函数对于任何类型的参数都是 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51590971/