我的问题很简单。这样做安全吗?
不需要任何道德建议,如“不要命名您的函数交换()!”或者随便什么拜托!
file1.hpp
//header guards here
#include <utility> //includes std::swap and std::move
namespace foo
{
template<typename T>
inline void swap(T& lhs, T& rhs)
{
T temp = std::move(lhs);
lhs = std::move(rhs);
rhs = std::move(temp);
}
}file2.cpp
#include "file1.hpp"
namespace foo
{
template<typename T>
void myfun(T a, T b)
{
a += b;
swap(a, b); //does it imply foo::swap, because the function
//is declared in the foo namespace??
}
}发布于 2016-01-04 20:09:40
这完全取决于T的类型。
如果swap()的类型与自己的交换空间位于不同的名称空间中,则依赖于参数的查找将发现不同的T。否则,它将在当前命名空间中查找。
#include <utility> //includes std::swap and std::move
#include <iostream>
namespace foo
{
template<typename T>
inline void swap(T& lhs, T& rhs) {
std::cout << "foo swap\n";
}
}
namespace foo
{
template<typename T>
void myfun(T a, T b)
{
a += b;
swap(a, b); // Looks for swap using the type T.
// If not found uses the current namespace.
// If not found uses the enclosing namespace.
}
}
namespace baz
{
class X {
public:
X& operator+=(X const& rhs){return *this;}
};
inline void swap(X& lhs, X& rhs) {
std::cout << "Bazz Swap\n";
}
}
int main()
{
baz::X a,b;
foo::myfun(a,b); // finds ::baz::swap()
}结果:
> a.out
Bazz Swap
>发布于 2016-01-04 19:55:43
它会叫foo::swap。
如果您想使用std::swap(a, b);实现,可以使用std
发布于 2016-01-04 20:02:45
是的,当然。首先搜索当前命名空间以查找非限定名。
https://stackoverflow.com/questions/34598778
复制相似问题