c++ - 模板化重载运算符不明确

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

我有一个容器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);
}

如何最好地解决歧义?

最佳答案

您需要提供一个重载模板,该模板在其不明确的参数上优于这两个模板:

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

关于c++ - 模板化重载运算符不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12071300/

相关文章:

c++ - 按值调用 vs 按引用调用 const

c++ - Wt中如何给表格添加滚动区域(机智)

C++ 模板结构 'has no member named' 错误

c++ - 三元运算符的结果不是右值

c++ - 抑制纯虚函数调用模态对话框并静默崩溃

c++ - 有什么方法可以避免跨类的不同构造函数进行代码复制?

html - Go 模板中的嵌套范围

使用派生类的 C++ 模板转换

c++ - 获取在运行时作为参数传递的重载函数的名称

c++ - 有没有什么方法可以在没有 std::move 的情况下调用 C++ 中的移动赋值运算符?