Reputation: 5092
Seems the compiler ignores the constexpr qualifier when it is added to a non-constexpr function. Why is that?
The following code compiles fine and runs.
#include <iostream>
#include <string>
using std::string; using std::cout; using std::endl;
constexpr bool is_shorter(const string &lft, const string &rht) // this is not a constexpr function
{
return lft.size() < rht.size();
}
int main()
{
bool restul = is_shorter("Hello", "World!");
return 0;
}
Upvotes: 0
Views: 83
Reputation: 180945
The reason this happens is because the standard allows it to do so. [dcl.constexpr]/5 states
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 (8.20), or, for a constructor, a constant initializer for some object (6.6.2), the program is ill-formed, no diagnostic required.
So, since the function can never be a core constant expression the behavior is undefined and the compiler is not required to notify you.
Upvotes: 3