1

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

4

1 回答 1

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: error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&)

于 2012-11-12T08:15:54.337 回答