由于constexpr的扩展版本(我想从C++ 14开始),你可以声明constexpr函数,它们可以用作"真正的"constexpr,即代码在编译时执行或者可以表现为内联函数.那么什么时候可以有这个程序:
#include <iostream>
constexpr int foo(const int s) {
return s + 4;
}
int main()
{
std::cout << foo(3) << std::endl;
const int bar = 3;
std::cout << foo(bar) << std::endl;
constexpr int a = 3;
std::cout << foo(a) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当然,结果是:
7
7
7
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.所以我的问题是:如果函数在编译时或运行时执行,有没有办法(可能是标准的)知道foo(const int s)?
编辑:也可以在运行时知道在编译时是否评估了函数?
我有一个Assert用于评估断言的函数:
如果前提条件在运行时失败,该函数将输出一条错误消息并终止程序。
如果常量表达式中的前提条件失败,则会导致编译时错误。
我希望当断言在常量计算表达式中失败时,该函数也会生成编译时错误:
const int a = (Assert(false),0); //generate a runtime error
//=> I would like it generates a compile time error
Run Code Online (Sandbox Code Playgroud)
我考虑过使用std::is_constant_evaluated:compiler-explorer
#include <type_traits>
using namespace std;
void runtime_error();
constexpr void compile_time_error(){} //should generates a compile time error
constexpr void Assert(bool value){
if (value) return;
if (is_constant_evaluated())
compile_time_error();
else
runtime_error();
}
void func(){
const int a = (Assert(false),0);
}
Run Code Online (Sandbox Code Playgroud)
我只使用 GCC,我寻找了一个会导致编译时错误的内置函数,该函数是 constexpr,但没有找到。
是否有任何技巧可以在可以常量求值的表达式中获得编译时错误?