覆盖 ADL 选择的重载
override an overload selected by ADL
我正在使用一个operator<<
有缺陷的库,我想用我自己的版本替换它。它遵循 ADL 根据参数在库命名空间中的成员身份选择重载的惯用语。有什么方法可以让C++选择我自己的operator<<
吗?
一个次优的解决方案是在库类型周围声明一个包装类。
一般实现如下所示:
/* Namespace-specific reference wrapper type.
Associates a function argument with the desired namespace.
Declare a new use_local_t for each namespace with an overriding overload */
template< typename t >
struct use_local_t
{ t ref; };
template< typename t >
use_local_t< t && >
use_local( t &&o )
{ return { std::forward< t >( o ) }; }
/* The overriding overload.
Instead of overloading on a specialization of use_local_t, use the
general template and enable_if. This allows for the various kinds of
references that use_local_t might forward, and conversion of the function
argument to the expected library_type parameter. */
template< typename t >
inline
typename std::enable_if<
std::is_convertible< t, library_type const & >::value,
std::ostream &
>::type
operator<< ( std::ostream &s, use_local_t< t > ul ) {
return s << ul.ref.foo;
}
std::cout << my_namespace::use_local( library_obj );
这经过测试,可与表达式模板配合使用。请注意,如果覆盖重载不匹配,则来自 GCC 4.7 的错误消息是红鲱鱼...它是指涉及流右值引用的std::
重载:
/opt/local/include/gcc47/c++/ostream:600:5:错误:初始化参数 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&)
相关文章:
- 添加重载更改选择的重载
- 具有参数包和通用引用的重载选择
- 重载模板函数未为特定类型选择正确的版本
- 为什么选择转换运算符的重载?
- 为什么传递文字 3 会选择 int 重载而不是短重载?
- 模板函数重载(泛型类型与模板模板类型)选择正确的重载
- 为什么<iostream>运算符<<会选择明显错误的重载?
- C++:使用重载而不是动态强制转换通过基选择派生类
- 模板实例化失败:编译器选择不正确的重载函数
- 编译器选择错误的重载函数
- 为什么重载分辨率不选择模板函数的 std::vector 重载?
- 如何获取通过重载分辨率选择的函子签名
- 一种类型特征,标识哪个类提供通过重载解析选择的函数
- 当参数不同时,重载分辨率不会选择模板
- 为什么 lambda 自动和参数选择常量重载?
- 方括号和圆括号操作器,如何选择重载
- 常量表达式来自重载函数的选择
- 强制编译器选择常量运算符重载
- 是否在重载选择期间未考虑默认参数的转换
- 构造函数重载选择了强制转换运算符而不是结构类型