一个constexpr函数可以调用返回void的函数吗? [英] Can a constexpr function call a function that returns void?

查看:167
本文介绍了一个constexpr函数可以调用返回void的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想做的:

void g() {
    std::cout << "smth1" << std::endl;
    std::cout << "smth2" << std::endl;
}

constexpr bool f() {return g(), true;}


b $ b

编译器( gcc version 4.8.2)不满意,因为 g 不是 constexpr 。是否可以解决这个问题?

The compiler (gcc version 4.8.2) is not happy with this, since g is not constexpr. Is it possible to get around this problem?

推荐答案

constexpr的意义是它可以在编译时完全展开。没有可能的方法,编译器可以将运行时副作用(使用 cout )放入有效的更复杂的编译时常量。换句话说:在运行时不会对 constexpr 函数进行实际的函数调用!

The point of constexpr is that it can be fully expanded at compile-time. There is no possible way that the compiler can put runtime side effects (using cout) into what is effectively a more complex compile-time constant. Put another way: No actual function call will be made at runtime for constexpr functions!

幸运的是,解决方案很容易!

Luckily the solution is easy!

f 更改为 constexpr bool f(){return true;}

Change f to constexpr bool f() { return true;}

且条件为:

g();
if(f())
{
    // ...
}

这篇关于一个constexpr函数可以调用返回void的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆