我有一个容器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/