c++ - C++ 如何说服 constexpr 函数是 constexpr,对于任何类型的参数
问题描述
我找不到与此相关的问题/答案。考虑一下:
// 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()
仅使用参数类型声明和实现。我是否公开违反标准中的一些明显规则?或者巧妙地,反对一些微妙的。
我谨慎地希望有人可以“解决”这个问题?
解决方案
我真的希望有人可以“解决”这个问题?
我看到的唯一“绕过”是 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()
.
推荐阅读
- bash - 使用 bash 解析 .env 文件并将其注入命令行
- python-3.x - 推特结构特别 - 转推 - 我的代码逻辑
- c# - 为什么 selenium chrome 驱动程序在后台运行(无头模式)
- git - 跳过 gitlab 管道中的上传文件夹
- android - 是否有适用于 iOS 和 Android 的 Xamarin.Form MediaPlayer?
- c# - 为什么我无法通过控制台窗口获取列表项的用户输入?
- c++ - 不同的别名模板能否解决跨库的潜在 ODR 违规问题?
- sql-server - 对存储过程的调用统计
- arrays - 如何以适当的方向构建多维数组。(行/列在正确的地方)
- mysql - 我无法打开我的 phpMyAdmin 页面我应该怎么做?[在MacBook上]