模板重载运算符不明确

Templated overloaded operator is ambiguous

本文关键字:不明确 运算符 重载      更新时间:2023-10-16

对于许多其他容器、表达式模板和文字类型U,我有一个容器template <typename T> class A,其operator+需要重载。

我目前的策略是定义一个模板函数wrap,它封装了如何访问各个元素并定义

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

然而,以下过载的operator+是不明确的:

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);
}

如何最好地解决歧义?

您需要提供一个重载模板,该模板在其不明确的参数上比两者都好:

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) -> ...;