C++ template functions with the same name but different return type

Viewed 1684

I am trying to make some file streamer that can read or write different types. Everything works except for the reading part with specific method. That method returns std::unique_ptr<T> when called and is a "wrapper" for another method that returns T. For some reason compiler does not use this method instead it tries to compile it with the other method (the one that returns T). The compilation fails because of this. I've already tried to search around internet but I can not find any accurate answer. Could you please help me with this.

The two methods I have defined:

template <typename T>
T read()
{
     T obj;
     obj.readFromFile<T>();
     return std::move(obj);
}

and

template <
  typename T,
  template<typename> class D,
  template<typename, typename> class Container
>
typename  std::enable_if_t<
  std::is_same<Container<T, D<T>>, std::unique_ptr<T, D<T>>>::value,
  Container<T, D<T>>
>
read()
{
    return std::move(std::make_unique<T, D<T>>(readFromFile<T>()));
}

The latter method is the one that I am trying to call.

When I write something like this:

std::unique_ptr<A> AfromFile = fileStreamer.read<std::unique_ptr<A>>()

compiler tries to compile it with the first method (template <typename T> T read() {...}) and the compilation fails. I could make this work if I made unique_ptr object first and than do the copy assignment to *unique_ptr<A> object but this is no good for me because i use some macro over those two functions and I cannot make unique_ptr<A> object or object A it self prior to calling the macro. Just for info I am using Visual Studio 2015.

Is there any way to make this work without any significant modification? I also found one suggestion that basically says you have to add a pointer parameter to one function and then call it with static_cast<Obj>(nullptr) as an argument but this does not count in my example.

Thanks for your help.

Update: I just want to make a remark that all solutions below did work for me however the easiest way to fix my problem was solution provided by Barry. Thx again for helping me!

3 Answers
Related