Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use decltype to determine the result of an addition

With decltype 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 T1 and T2. Concretely:

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

Of course, decltype(ValueType+CompatibleType) does not work this way. Is there any way I can achieve this?

like image 810
nijansen Avatar asked Nov 29 '22 01:11

nijansen


2 Answers

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) +
                   *static_cast<CompatibleType*>(0))>
like image 117
David G Avatar answered Dec 01 '22 16:12

David G


You could use std::declval for that:

decltype(std::declval<A>()+std::declval<B>))
like image 44
PlasmaHH Avatar answered Dec 01 '22 16:12

PlasmaHH