我正在尝试为我的模板类编写一个operator|
boo
并且一切正常,直到模板类是提升范围类型 - 就像在示例中一样boost::range::filter_range
- adl 更喜欢boost::range_detail::operator|(SinglePassRange& r, const replace_holder<T>)
而不是本地。
谁能解释为什么 adl 更喜欢来自 boost 这个详细命名空间的重载而不是本地命名空间?
#include <vector>
#include <boost/range/adaptors.hpp>
namespace local
{
template<typename T>
struct boo {};
// this overload is not prefered when T is a boost::range::xxx_range
template<typename T, typename U>
auto operator|(boo<T>, U)
{
return false;
}
void finds_local_operator_overload()
{
std::vector<int> xs;
// works like expected and calls local::operator|
auto f = boo<decltype(xs)>{} | xs;
}
void prefers_boost_range_detail_replaced_operator_overload_instead_of_local_operator()
{
std::vector<int> xs;
// compiler error because it tries to call 'boost::range_detail::operator|'
auto filtered = xs | boost::adaptors::filtered([](auto &&x){ return x % 2; });
auto f = boo<decltype(filtered)>{} | xs;
}
}
CLANG 错误(MSVC 报告几乎相同):
/xxx/../../thirdparty/boost/1.60.0/dist/boost/range/value_type.hpp:26:70: error: no type named 'type' in
'boost::range_iterator<local::boo<boost::range_detail::filtered_range<(lambda at
/xxx/Tests.cpp:221:49), std::vector<int, std::allocator<int> > > >, void>'
struct range_value : iterator_value< typename range_iterator<T>::type >
~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
/xxx/../../thirdparty/boost/1.60.0/dist/boost/range/adaptor/replaced.hpp:122:40: note: in instantiation of template class
'boost::range_value<local::boo<boost::range_detail::filtered_range<(lambda at
/xxx/Tests.cpp:221:49), std::vector<int, std::allocator<int> > > > >' requested
here
BOOST_DEDUCED_TYPENAME range_value<SinglePassRange>::type>& f)
^
/xxx/Tests.cpp:222:37: note: while substituting deduced template arguments into
function template 'operator|' [with SinglePassRange = local::boo<boost::range_detail::filtered_range<(lambda at
/xxx/Tests.cpp:221:49), std::vector<int, std::allocator<int> > > >]
auto f = boo<decltype(filtered)>{} | xs;
根据 ADL 的规则, 在集合中添加的命名空间和类用于boo<decltype(filtered)>{} | xs
的重载是local
(对于boo
)、boost::range_detail
(对于decltype(filtered)
)和std
(对于std::vector<int>
xs
)。
我们特别有:
(如您所料,您的local
template<typename T, typename U> auto operator|(boo<T>, U);
和 )
boost::range_detail
中一个有问题的:
template <class SinglePassRange>
replaced_range<const SinglePassRange>
operator|(
const SinglePassRange&,
const replace_holder<typename range_value<SinglePassRange>::type>&);
所以我们有非推断range_value<boo<decltype(filtered)>>::type
,这会引起一个硬错误。(不幸的是,该方法对SFINAE不友好,无法从过载集中移除)。
错误发生在overload_resolution之前。