覆盖ADL选择的过载

时间:2012-11-12 08:11:50

标签: c++ operator-overloading argument-dependent-lookup using-declaration

我正在使用一个有缺陷operator<<的库,我想用自己的版本替换它。它遵循惯用法,其中ADL根据参数在库名称空间中的成员资格选择重载。有没有办法让C ++选择我自己的operator<<

1 个答案:

答案 0 :(得分:1)

一个次优的解决方案是在库类型周围声明一个包装类。

一般实现如下:

/* 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&lt; _CharT,_Traits&gt;&amp;的参数1 std :: operator&lt;&lt;(std :: basic_ostream&lt; _CharT,_Traits&gt;&amp;&amp;,const _Tp&amp;)