Question

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.

Was it helpful?

Solution

If you call a constexpr function using non-constant expressions as its arguments, the function is executed on runtime.

If you do this:

constexpr someType dummy = fma(someType(), someType(), someType());

it will fail, since you are forcing the result to be stored in a constexpr type. That can't be done in compile-time, therefore you get a compile error.

Note that this would work if you provided both a constexpr constructor and a constexpr operator+/* in someType.

OTHER TIPS

From section 7.1.5.6 of the C++11 standard:

If the instantiated template specialization of a constexpr function template or member function of a class
template would fail to satisfy the requirements for a constexpr function or constexpr constructor, that
specialization is not a constexpr function or constexpr constructor. [ Note: If the function is a member
function it will still be const as described below. — end note ] If no specialization of the template would
yield a constexpr function or constexpr constructor, the program is ill-formed; no diagnostic required.

This means that a constexpr function template degrades to a non-constexpr function if it is instantiated with template parameters which make it not be a valid constexpr function.

If it wouldn't be a valid constexpr function no matter what template parameters you gave it, then the compiler may complain, but it doesn't have to.

Since templates are mostly checked for errors on use, only when you use it with a type with non constexpr operators it will error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top