Consider the following code:
template<typename T>
constexpr inline T fma(T a, T b, T c)
{
return a * b + c;
}
This compiles just fine. But why does it? In theory, constexpr functions can only call other constexpr functions. However, there is no guarantee that the operators will be constexpr functions. For example, let’s say I have some type with the following interface:
class someType
{
someType operator + (const someType &rhs);
someType operator * (const someType &rhs);
};
The operators + and * are not constexpr. If I write the following code:
fma(someType(), someType(), someType());
It should fail to compile because a constexpr function is calling non-constexpr functions. But it compiles just fine. Why is this?
I’m using MinGW’s G++ compiler with the -std=c++0x option.
If you call a constexpr function using non-constant expressions as its arguments, the function is executed on runtime.
If you do this:
it will fail, since you are forcing the result to be stored in a
constexprtype. That can’t be done in compile-time, therefore you get a compile error.Note that this would work if you provided both a
constexprconstructor and aconstexproperator+/*insomeType.