3 ms·
The problem with the technique used by Eigen (and also Boost.Spirit among a few other famous libs), called expression templates, is that it leverages the fact t
by jcelerier 8y ago
The problem with the technique used by Eigen (and also Boost.Spirit among a few other famous libs), called expression templates, is that it leverages the fact that the references to temporaries in function calls will be maintained until the end of the expression. The last operation in the expression (assignment to a specific type) will do processing to preserve those temporaries, compute the result, etc...
e.g. it more or less looks like this in a trivial case :
#include <cstdio>
template<typename T1, typename T2>
struct add {
add(const T1& t1, const T2& t2): lhs{t1}, rhs{t2} { }
const T1& lhs;
const T2& rhs;
constexpr auto get() const { return lhs.get() + rhs.get(); }
};
struct integer
{
const int& i;
constexpr const int& get() const { return i; }
};
int f();
int main()
{
auto x = add{add{integer{f()}, integer{f()}}, add{integer{f()}, integer{f()}}};
}
Here, storing the value in `auto` is wrong because by the time the expression has ended, the references point to stuff that isn't in scope anymore
Hence the solution is to introduce a type that will actually do the computation or store the result during the expression ; but before C++11 you had to introduce a type here anyways, which is what was done and of course it worked.