std::(customization point) 是否调用最合适的重载?
Does std::(customization point) invoke the most appropriate overload?
从C++20开始,在[namespace.std]/7中引入了自定义点的概念:
Other than in namespace std or in a namespace within namespace std, a program may provide an overload for any library function template designated as a customization point, provided that (a) the overload's declaration depends on at least one user-defined type and (b) the overload meets the standard library requirements for the customization point. [ Note: This permits a (qualified or unqualified) call to the customization point to invoke the most appropriate overload for the given arguments. — end note ]
注释部分(注意强调的词"qualified")是否意味着如果std::f
是自定义点,std::f
将自动为f
调用最合适的重载?
一个真实的例子是std::swap
, which is a designated customization point. Does this mean since C++20, we can write std::swap(a, b)
directly instead of using std::swap; swap(a, b);
?
A real example is std::swap
, which is a designated customization point. Does this mean since C++20, we can write std::swap(a, b)
directly instead of using std::swap; swap(a, b);
?
没有。 std::swap
本身没有获得任何权力。它仍然只是一个函数模板,所以如果你直接调用它,你就是……直接调用它。没有 ADL 或任何东西。
这里的重点是说如何 自定义点应该被选择。也就是你写:
namespace N { // not std
void swap(Foo&, Foo&);
}
不是:
namespace std {
void swap(N::Foo&, N::Foo&);
}
也不是:
namespace std {
template <>
void swap(N::Foo&, N::Foo&);
}
但是,C++20 确实引入了很多称为 customization point objects which you can use directly do this kind of thing. The CPO for swap
is spelled std::ranges::swap
的新东西(同样,所有有用范围的东西都有 CPO...ranges::begin
、ranges::end
等)。
从C++20开始,在[namespace.std]/7中引入了自定义点的概念:
Other than in namespace std or in a namespace within namespace std, a program may provide an overload for any library function template designated as a customization point, provided that (a) the overload's declaration depends on at least one user-defined type and (b) the overload meets the standard library requirements for the customization point. [ Note: This permits a (qualified or unqualified) call to the customization point to invoke the most appropriate overload for the given arguments. — end note ]
注释部分(注意强调的词"qualified")是否意味着如果std::f
是自定义点,std::f
将自动为f
调用最合适的重载?
一个真实的例子是std::swap
, which is a designated customization point. Does this mean since C++20, we can write std::swap(a, b)
directly instead of using std::swap; swap(a, b);
?
A real example is
std::swap
, which is a designated customization point. Does this mean since C++20, we can writestd::swap(a, b)
directly instead of usingstd::swap; swap(a, b);
?
没有。 std::swap
本身没有获得任何权力。它仍然只是一个函数模板,所以如果你直接调用它,你就是……直接调用它。没有 ADL 或任何东西。
这里的重点是说如何 自定义点应该被选择。也就是你写:
namespace N { // not std
void swap(Foo&, Foo&);
}
不是:
namespace std {
void swap(N::Foo&, N::Foo&);
}
也不是:
namespace std {
template <>
void swap(N::Foo&, N::Foo&);
}
但是,C++20 确实引入了很多称为 customization point objects which you can use directly do this kind of thing. The CPO for swap
is spelled std::ranges::swap
的新东西(同样,所有有用范围的东西都有 CPO...ranges::begin
、ranges::end
等)。