C++ 如何让 constexpr 函数对于任何类型的参数都是 constexpr

标签 c++ c++17 constexpr constant-expression

我找不到与此相关的问题/答案。考虑一下:

// 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() 仅使用参数类型进行声明和实现。我是否公开违反标准中的某些明显规则?或者巧妙地对抗一些微妙的。

我谨慎地希望有人能够“解决”这个问题?

Code is here

最佳答案

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/

相关文章:

c++ - 使用具有由字符串 C++ 定义的 map 名称的 map

c++ - 在 ubuntu 上安装 npm 期间,使用 C++ 17 编译 native Node 插件失败

c++ - 类内的静态 constexpr 初始化链

c++ - __builtin_ctz(0) 或 __builtin_clz(0) 的未定义程度如何?

c++ - 对于函数 : constexpr const or enum? 中的常量,我应该更喜欢哪个

c++ - cocos2d-x 3.8 - 使用网络扩展

c++ - 无法删除作为类字段的数组

java - 图像跟踪器库

c++ - 我需要在 else-if 之后加上 constexpr 吗?

c++ - 如果类型是在之后定义的,则实例化具有不完整类型的类模板是否格式错误?