Search⌘ K
AI Features

Evaluation Order in C++17

Explore the changes in evaluation order introduced in C++17 that ensure inner expressions and operator overloads are executed from left to right. Understand how this impacts function chaining and operator overloading behavior, improving code clarity and predictability.

The example case

C++ 17
#include <iostream>
class Query
{
public:
Query& addInt(int i)
{
std::cout << "addInt: " << i << '\n';
return *this;
}
Query& addFloat(float f)
{
std::cout << "addFloat: " << f << '\n';
return *this;
}
};
float computeFloat()
{
std::cout << "computing float... \n";
return 10.1f;
}
float computeInt()
{
std::cout << "computing int... \n";
return 8;
}
int main()
{
Query q;
q.addFloat(computeFloat()).addInt(computeInt());
}

You probably expect that using C++14 computeInt() happens after addFloat. Unfortunately, that might not be the case. For instance here’s an output ...