[英]What's the difference between std::ranges::swap() and std::swap()?
[英]How do I make std::sort not have name collision between std::swap and my namespace's templated swap?
我想使用std::sort
,但是编译失败,错误C2668: std::swap: ambiguous call to overloaded function
因为在我的命名空间中定义了一个模板化swap()
函数,这很难摆脱。 我不在乎它使用哪个swap
,但是在编译sort()
时如何使其中任何一个消失?
我知道它是模棱两可的,因为my::swap
与my::Obj
在同一个命名空间中,而且我不在乎使用哪个版本的swap
。 我只需要克服名称空间冲突。 这是我不拥有的非常大的代码库的一部分,因此我希望找到一种对我的代码而言本地的解决方案,并且可能允许my::Obj
和my::swap
都保留在my
命名空间中。
namespace my
{
template<class T> void swap(T a, T b)
{
}
struct Obj
{
};
void doSortStuff()
{
std::vector<Obj> arr;
std::sort(arr.begin(), arr.end());
}
};
一种解决方法是创建更好的重载:
// No modifiable code
namespace my
{
template<class T> void swap(T a, T b) { /*.. */ }
struct Obj { /*..*/ };
}
// Your code:
namespace my
{
void swap(Obj& lhs, Obj& rhs)
{
// my::swap<Obj&>(lhs, rhs);
std::swap(lhs, rhs);
}
}
// In namespace you want.
void doSortStuff()
{
std::vector<my::Obj> arr;
std::sort(arr.begin(), arr.end());
}
然后,在3个有效的重载之间,所有的重载都是完全匹配的,但首选非模板。
与某些评论相反,有些令人惊讶的是,在不using namespace std
情况下会发生此错误。 这是一个了解发生了什么的最小示例:
namespace like_std
{
template<class T> void swap(T a, T b) {}
template <class T> auto test(T x, T y)
{
swap(x, y); // (1) ambiguous call
}
}
namespace my
{
template<class T> void swap(T a, T b) {}
struct Obj {};
void doStuff()
{
like_std::test(Obj{}, Obj{});
}
};
您从like_std
调用了一个函数,并且在此函数内部有一个不合格的swap
调用。 对于此呼叫:
like_std::swap
是候选对象,因为它与swap
调用位于同一名称空间中
my::swap
因为ADL而成为候选对象:之所以引入它是因为它与调用swap
的参数之一在同一名称空间中
由于这些都不是更好,因此存在歧义。
调用swap
不合格的原因是,这样可以在定义了自定义swap
情况下使用自定义swap
, 但是只有在自定义swap
是更好的候选者(自定义swap
函数假定)的情况下,该调用才有效。
如Jarod42所示,解决方案是定义更好的候选swap
函数。
您可能正在using namespace std;
。
在这种情况下,编译器不知道要选择什么,因为它使所有std::
成员都可用而没有自动键入,这两个函数都适用:
using namespace std;
swap(a, b); //your swap
swap(a, b); //std::swap
在这种情况下,您必须执行严格的函数调用:
std::swap(a, b); //from std
swap(a, b); // your one
这实际上是一个很好的示例,说明了为什么应避免using namespace std
。 祝好运!
更新:这可能是您的解决方案-将swap()
移到std::sort()
用法之外:
#include <algorithm>
#include <vector>
namespace detail
{
struct someContainer
{
someContainer(int &v)
{
value = v;
}
int value;
someContainer &operator = (const someContainer & rhs)
{
this->value = rhs.value;
}
bool operator == (someContainer &rhs) const
{
return this->value == rhs.value;
}
bool operator <= (someContainer &rhs) const
{
return this->value <= rhs.value;
}
bool operator >= (someContainer &rhs) const
{
return this->value >= rhs.value;
}
bool operator > (someContainer &rhs) cosnt
{
return this->value > rhs.value;
}
bool operator < (someContainer &rhs) const
{
return this->value < rhs.value;
}
};
void doSomeStuff()
{
std::vector<someContainer> vec;
for (int i = 0; i < vec.size(); ++i)
{
vec.push_back(someContainer(i));
}
std::sort(vec.begin(), vec.end());
}
}
namespace mySwap
{
template< class T >
void swap(T &a, T &b)
{
T c = a;
a = b;
b = c;
}
}
int main()
{
detail::doSomeStuff();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.