jk4736
jk4736

Reputation: 261

Templated overloaded operator is ambiguous

I have a container template <typename T> class A whose operator+ needs to be overloaded for many other containers, for expression templates and for literal types U.

My current strategy is to define a template function wrap that encapsulates how individual elements are accessed and define

template <typename T, typename U>
auto operator+(Wrapped<T>&& lhs, Wrapped<U>&& rhs) -> decltype(...)
{
    ....
}

The following overloaded operator+, however, is ambiguous:

template <typename T, typename U>
auto operator+(const A<T>& lhs, U&& rhs) ->
    decltype(wrap(lhs) + wrap(std::forward<U>(rhs)))
{
    return wrap(lhs) + wrap(std::forward<U>(rhs));
}

template <typename T, typename U>
auto operator+(T&& lhs, const A<U>& rhs) ->
    decltype(wrap(std::forward<T>(lhs)) + wrap(rhs))
{
    return wrap(std::forward<T>(lhs)) + wrap(rhs);
}

How can I resolve the ambiguity best?

Upvotes: 2

Views: 728

Answers (1)

ecatmur
ecatmur

Reputation: 157334

You need to provide an overload template that's better than both on the arguments it's ambiguous for:

template<typename T>
auto operator+(const A<T> &lhs, const A<T> &rhs) -> ...;

template<typename T, typename U>
auto operator+(const A<T> &lhs, const A<U> &rhs) -> ...;

Upvotes: 2

Related Questions