【发布时间】:2015-01-22 00:16:57
【问题描述】:
考虑代码:
#include <iostream>
#include <algorithm> // std::swap C++98
#include <utility> // std::swap C++11
namespace A
{
template<typename T>
struct Foo {};
template<typename T>
void swap(Foo<T> &lhs, Foo<T> &rhs)
{
std::cout << "A::swap<T>" << std::endl;
}
} /* end namespace A */
namespace std // we explicitly specialize std::swap here
{
template<> // explicit template specialization for std::swap<int>
void swap(A::Foo<int> &lhs, A::Foo<int> &rhs)
noexcept
(is_nothrow_move_constructible<A::Foo<int>>::value && is_nothrow_move_assignable<A::Foo<int>>::value)
{
std::cout << "std::swap<int>" << std::endl;
}
} /* end namespace std */
int main()
{
using std::swap;
A::Foo<int> a, b;
A::Foo<double> x, y;
swap(a, b); // ADL, expected to call std::swap<Foo<int>>, but NO
swap(x, y); // ADL, expected to call A::swap<T>, YES
}
我希望std::swap 显式特化在调用swap(a, b) 中是更好的候选者,但是似乎重载 A::swap 总是首选,即输出是:
A::swap<T> A::swap<T>
谁能解释为什么会出现这种行为?
【问题讨论】:
-
Herb Sutter 的这篇优秀文章可能会让您感兴趣:Why Not Specialize Function Templates?
标签: c++ templates c++11 overloading argument-dependent-lookup