constexpr and std::cout working on function but not in lambda

有些话、适合烂在心里 提交于 2019-11-29 14:46:18

问题


Why constexpr does not work with std::cout, but works with printf?

#include <iostream>
constexpr void f() { std::cout << ""; } //error
constexpr void g() { printf(""); } //ok

And why std::cout works with lambdas constexpr?

#include <iostream>
int main () {
    auto h = []() constexpr { std::cout << ""; }; //ok
}

回答1:


Technically, it doesn't work with any of them.

From [dcl.constexr]:

For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression, or, for a constructor, a constant initializer for some object ([basic.start.static]), the program is ill-formed, no diagnostic required.

f() and g() are never constant expressions (neither std::cout << x nor printf() are constexpr functions), so the constexpr declaration is ill-formed. But the compiler isn't required to diagnose this (in this case, it may be easy, but in the general case... not so much). What you're seeing is that your compiler was able to diagnose one problem but not the other.

But they're both wrong.




回答2:


It doesn't. You need to use it to force a compile time error.

constexpr int a = f(), 0; // fails
constexpr int b = g(), 0; // fails

constexpr functions that never produce a constant expression are ill-formed; no diagnostic required. This means that compilers do a best effort check to see if that is the case, but your program already has an error either way. Seems like gcc can't see that printf is not a constant expression. clang errors at the definition.



来源:https://stackoverflow.com/questions/56568230/constexpr-and-stdcout-working-on-function-but-not-in-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!