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?
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))>
You could use std::declval
for that:
decltype(std::declval<A>()+std::declval<B>))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With