问题
Item 15 of Scott Meyer's Modern C++ book: "use constexpr whenever possible". He says you can mark a function constexpr and still call it with values that aren't known at compile-time -- in that case it'll behave like any other runtime function, so you get the benefits of compile-time computation if possible but can still use it with non-compile time values too. The compiler will figure it out. But if that's true, then why can't we tag every function with constexpr (or better yet, don't tag any of them and let the compiler figure it out all the time)? If the compiler is able to detect whether the values are known at compile-time and automatically do the right thing when I tag the method as constexpr, then why can't it automatically do that same check even when I don't write constexpr?
回答1:
... when the function receives values which are not known in compile-time. You cannot mark a function to be constexpr
if its computation depends on the value of a pointer, or a global value, etc, etc.
If the body
of that function can be executed in compile time, you can mark it as constexpr
, but you can still call it with runtime values. E.g., to be used for both, to calculate a static const value of a parametric class, using a compilation-time value passed as parameter, but also, to calculate a user value after getting its parameter through std::cin
.
whenever possible
... if the function body uses I/O operations, non-const global/static/-member) values, addresses or volatile
s, to name a few, is not possible.
来源:https://stackoverflow.com/questions/39795170/why-cant-c-automatically-figure-out-when-to-use-constexpr-without-making-us-w