nijansen nijansen - 3 years ago 99
C++ Question

How to use decltype to determine the result of an addition


I can do the following:

template <typename T1, typename T2>
auto sum(T1 const & t1, T2 const & T2)
-> decltype(t1+t2)
{ /* ... */ }

However, in my case I need to find out the type of an addition without having instances of the types
. Concretely:

template <typename ValueType>
class Matrix
/* ... */
template <typename CompatibleType>
auto operator+(Matrix<CompatibleType> const & other)
-> Matrix<decltype(ValueType+CompatibleType)>
{ /* ... */ }

Of course,
does not work this way. Is there any way I can achieve this?

Answer Source

Use std::declval<T>(); (C++11):

#include <utility>

template <typename CompatibleType>
 auto operator+(Matrix<CompatibleType> const & other)
  -> Matrix<decltype(std::declval<ValueType>() + std::declval<CompatibleType>())>
    { /* ... */ }

std::declval returns an rvalue-reference, and will only work in an unevaluated-context, which decltype happens to be.

If your compiler doesn't support this Standard, use this pointer trick (which also only works in an unevaluated-context):

-> Matrix<decltype(*(ValueType*)(0) + *(CompatibleType*)(0))>
// or
-> Matrix<decltype(*static_cast<ValueType*>(0) +
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download