假设我有这段代码:
#include <iostream>
constexpr int myDumbFunction(int a, bool b);
int main(int argc, char **argv) {
constexpr auto foo = 0;
const auto bar = 0;
//! compile-time execution:
std::cout << myDumbFunction(foo, true);
//! runtime execution:
std::cout << myDumbFunction(bar, true);
return 0;
}
constexpr int myDumbFunction(int a, bool b) {
if(a > 100 and b) {
return a - 100;
}
else if(a < 100 and b) {
return a + 100;
}
return 122;
}
有没有办法检测在编译时是否会调用第一个myDumbFunction()
函数调用?
在这个特殊的例子中,它非常明显,但是让我说我不知道有关我正在传递的物体的所有细节。
另一个constexpr
相关问题:是否存在一些不会改变编译时执行的断言?
答案 0 :(得分:4)
std::cout << std::integral_constant<int, myDumbFunction(foo, true)>::value;
只有在编译时评估myDumbFunction
时,才有效。