让我们考虑以下代码:
#include <type_traits>
int foo(int arg) {
if (std::is_constant_evaluated()) {
return 1;
} else {
return 0;
}
}
int main() {
const auto b = foo(0);
return b;
}
Run Code Online (Sandbox Code Playgroud)
它用gcc 和 clang返回 0 。我原以为它会返回 1 。
如果foo()是 made constexpr, whileb被简单地保留const,那么它确实返回 1 。
我在这里缺少什么?谢谢!
我已经阅读了std::is_constant_evaluated()定义,但是我仍然不确定为什么(1)无法在最新的GCC上运行:error: 'x' is not a constant expression
template<auto v>
struct s
{};
constexpr void f(int x)
{
if (std::is_constant_evaluated())
{
// constexpr int z=x; (1)
// s<x> a; (2)
}
}
int main(int argc, char* argv[])
{
f(4);
//f(argc);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
随着分支 std::is_constant_evaluated()
更新
我可以将“解释性”信息“传输”到函数中吗?基本上决定f()是否使用constexprx 进行调用。
UPDATE 关于我要实现的目标的一个更复杂的示例:如果可能,此示例应在编译时对参数进行字符串化。
template<auto v>
struct dummy_stringify
{
static constexpr auto str=v==4 ? "4" : "31"; // this is just …Run Code Online (Sandbox Code Playgroud) 这是来自 cppreference 的示例:
constexpr double power(double b, int x)
{
if (std::is_constant_evaluated() && !(b == 0.0 && x < 0)) {
// A constant-evaluation context: Use a constexpr-friendly algorithm.
if (x == 0)
return 1.0;
double r = 1.0, p = x > 0 ? b : 1.0 / b;
auto u = unsigned(x > 0 ? x : -x);
while (u != 0) {
if (u & 1) r *= p;
u /= 2;
p *= p;
}
return …Run Code Online (Sandbox Code Playgroud)