Austin Hastings
Austin Hastings

Reputation: 627

Determine type of result of expression involving template type parameters?

Using c++11:

I'd like to declare a type that is the result of subtracting two template parameter type values.

How can I encode this in my template?

Example:

template<typename T>
class C {
    typedef T member_t;
    typedef TYPE_OF_RESULT_OF( T - T ) member_diff_t;
};

What would be the replacement for "TYPE_OF_RESULT_OF( T - T )" in the above?

I am expecting to compute a signed difference from any arithmetic type. So I suppose I could use as_signed(T). But it seems more correct to ask the compiler, if that makes sense.

Upvotes: 3

Views: 165

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477660

A simple solution would be this:

#include <type_traits>

using member_diff_t = typename std::decay<
    decltype(std::declval<T>() - std::declval<T>())>::type;

The decay makes sure that you get the naked type, with references stripped, in case the operation returns a reference.

Upvotes: 7

Related Questions