Simon Goodman Simon Goodman - 3 months ago 5
C++ Question

Template return by value, and pointer in cpp/h

In my header file I have a function

template<class T>
T Sum( T a, T b) const;


And it returns a value, so I can call

auto x = Sum<int>( 10, 10 );


But I would like to also be able to return a pointer

auto y = Sum<int*>(10, 10 );


But how can I define in the header class and in the source file to return either a pointer or a value

// return value
template <class T>
T Sum (T a, T b)
{
T result;
result = a + b;
return result;
}

// return as a pointer
template <class T>
T* Sum (T a, T b)
{
T result = new T();
*result = a + b;
return result;
}

Answer

No easy solution. Class templates have partial specialization, which allows you to specialize for all pointer types. But functions only have complete specialization. You can write

template <>
int* Sum<int*> (int a, int b)
{
  int result = new int();
  *result = a + b;
  return result;
}

Now, a class template and its partial specialization can have a static method, which is a viable workaround. Alternatively, use std::enable_if and std::is_pointer to define two unrelated Sum<> templates, one of which is enabled for pointers and one which is NOT enabled for pointers.