使用'constexpr'参数以区分编译器已知值并因此能够在编译时检测错误将是有用的.例子:
int do_something(constexpr int x)
{
static_assert(x > 0, "x must be > 0");
return x + 5;
}
int do_something(int x)
{
if(x > 0) { cout << "x must be > 0" << endl; exit(-1); }
return x + 5;
}
int var;
do_something(9); //instance 'do_something(constexpr int x)' and check arg validity at compile-time
do_something(0); //produces compiler-error
do_something(var); //instance 'do_something(int x)'
Run Code Online (Sandbox Code Playgroud)
这是目前无效的代码.有人可以解释一下为什么这不能实现吗?
编辑:
使用模板用户应该确保文字总是作为模板参数传递,而不是作为非常不舒服的函数传递:
template<int x>
int do_something()
{
static_assert(x > 0, "x must be > 0");
return …Run Code Online (Sandbox Code Playgroud) 当前,即使对它的所有调用确实为,也无法用于static_assert验证constexpr函数的参数constexpr。这是有道理的,因为在某些其他模块尝试调用该函数的情况下,编译器仍必须为此函数创建一个非constexpr实例。可悲的是,即使函数是static或位于匿名名称空间中,也是如此。
然而,C ++ 20将引入一个新的关键字consteval,类似于constexpr但不允许以非constexpr的方式调用函数。在这种情况下,编译器可以确定在编译时始终知道函数参数。因此,从理论上讲,应该有可能使用进行验证static_assert。
问题是:标准允许吗?
例:
#include <iostream>
consteval char operator""_bchar(const char text[], const size_t length)
{
static_assert(length == 8, "Binary char has to have 8 digits!"); // <-- This is currently not possible.
uint8_t byte = 0;
for (size_t i = 0; i != length; ++i)
{
byte <<= 1;
byte |= text[i] == '1' ? 0b00000001 : 0b00000000;
}
return byte;
}
int main() …Run Code Online (Sandbox Code Playgroud)