【发布时间】:2018-05-03 03:46:12
【问题描述】:
因为正确使用 std::swap 是:
using std::swap;
swap(a,b);
这有点冗长,但它确保如果 a,b 有更好的交换定义,它就会被选中。
所以现在我的问题是为什么std::swap 没有使用这种技术实现,所以用户代码只需要调用std::swap?
这样的事情(忽略noexcept 和简洁的约束):
namespace std {
namespace internal {
template <class T> // normal swap implementation
void swap(T& a, T& b) { // not intended to be called directly
T tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
}
template <class T>
void swap(T& a, T& b) {
using internal::swap;
swap(a,b);
}
}
【问题讨论】:
-
可能会破坏很多现有代码。名称冲突或行为改变。
-
抱歉,我在这里遗漏了什么吗?
std::internal_do_not_use_directly::swap;应该是什么? -
Neil Butterworth - 正如评论用很少的话说的:),它与当前的 std::swap 具有相同的实现;
-
@NeilButterworth 我相信他提议的是
std::swap,而实际的std::swap应该在std::internal_do_not_use_directly::swap中实现 -
@NoSenseEtAl:这不是无限递归到底是怎么回事?还是重载决议冲突?毕竟,这两个函数具有相同的签名和名称;什么会阻止编译器调用自己?
标签: c++ argument-dependent-lookup template-function customization-point