【问题标题】:Templated overloaded operator is ambiguous模板化重载运算符不明确
【发布时间】:2012-08-22 10:38:52
【问题描述】:

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

我目前的策略是定义一个模板函数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);
}

如何最好地解决歧义?

【问题讨论】:

    标签: c++ templates c++11 operator-overloading


    【解决方案1】:

    你需要提供一个重载模板,它比这两个参数都更好:

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

    【讨论】:

    • 我的想法是一样的。但是,我仍然会感到过载。
    • @jk4736 如果您发布更多代码,可能会告诉您如何解决歧义。什么论据是模棱两可的?
    • 哦!可能是因为 operator+ 是用右值 A 调用的吗?
    • @jk4736 很可能;我以为你已经超载了。
    • 是的,我测试过了,额外的重载解决了这个问题。有没有办法避免代码重复?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多