Search code examples
c++template-argument-deduction

C++ function template argument deduction


I have a class template for the smart pointers of which I want an operator+()

template<typename T, typename U>
class Foo{};

template<typename T, typename U>
std::unique_ptr<Foo<T,U>> operator+(std::shared_ptr<const Foo<T, U>>, std::shared_ptr<const Foo<T, U>>);

I now want the following to work with tempate argument deduction:

std::shared_ptr<Foo<T, U>> a, b, c;

auto d = a + b + c;

It doesn't of course, because a and b are pointers to non-const, rather than pointers to const. It also doesn't work because a + b is a unique pointer rather than a shared pointer.

Is there an elegant solution to make this deduction work? With an operator, I really don't want to explicitly specify the template arguments. The only sort-of feasible way I see is to overload operator+ for all permutations of shared_ptr and unique_ptr as well as const and non-const, but that's 16 function definitions to write.


Solution

  • Implement a template taking const references to Foo and then create another template using arbitary parameters that use this implementation.

    The following creates always returns unique_ptr containing a default initialized Foo.

    template<typename T, typename U>
    class Foo{};
    
    template<typename T, typename U>
    std::unique_ptr<Foo<T,U>> add_foos(const Foo<T, U>& f1, const Foo<T, U>& f2)
    {
        return std::make_unique<Foo<T, U>>();
    }
    
    template<typename T, typename U>
    auto operator+(T t, U u)
    {
        // use the function above here
        return add_foos(*t, *u);
    }
    

    Edit:

    Used @NathanOlivers suggestion from the comments: it would be preferrable not to make this apply for operands not related to Foo