Search code examples
c++templatesarithmetic-expressionstype-deduction

Deducing type of template parameter expression


How can the type of an template argument expression be deduced? For example, regarding the following code:

template< typename T >
class A
{
//....
};

template< typename T_1, typename T_2 >
class B
{
  auto foo()
  {
    return A</* Type of "T_1+T_2"*/>();
  }
};

How can the type of T_1+T_2 be deduced? For example, it could be T_1=float and T_2=intand consequently, foo should return A<float>() (since summing up an an integer with a float results in a float).


Solution

  • You can use a combination of decltype and std::declval. I would also suggest to typedef the result type for better readability:

    template< typename T_1, typename T_2 >
    class B
    {
      typedef decltype(std::declval<T_1>() + std::declval<T_2>()) result_type;
      auto foo() -> result_type
      {
        return A<result_type>();
      }
    };