c++ - 关于 reference_wrapper 和可调用对象

标签 c++ reference tr1 callable

给定以下可调用对象:

struct callable : public std::unary_function <void, void>
{
    void
    operator()() const
    {
        std::cout << "hello world" << std::endl;
    }
};  

一个std::tr1::reference_wrapper<>通过它调用:

callable obj;
std::tr1::ref(obj)();

相反,当 operator()接受一个参数:

struct callable : public std::unary_function <int, void>
{
    void
    operator()(int n) const
    {
        std::cout << n << std::endl;
    }
};  

std::tr1::bind接受它的 reference_wrapper 作为可调用包装器...

callable obj;
std::tr1::bind( std::tr1::ref(obj), 42 )();

但这有什么问题呢?

std::tr1::ref(obj)(42);

g++-4.4 编译失败,出现以下错误:

test.cpp:17: error: no match for call to ‘(std::tr1::reference_wrapper<const callable>) (int)’
/usr/include/c++/4.4/tr1_impl/functional:462: note: candidates are: typename std::tr1::result_of<typename std::tr1::_Function_to_function_pointer<_Tp, std::tr1::is_function::value>::type(_Args ...)>::type std::tr1::reference_wrapper<_Tp>::operator()(_Args& ...) const [with _Args = int, _Tp = const callable]

最佳答案

g++-4.4的tr1 reference_wrapper的实现配备了如下算子:

  template<typename... _Args>
    typename result_of<_M_func_type(_Args...)>::type
    operator()(_Args&... __args) const
    {
      return __invoke(get(), __args...);
    }

它通过引用获取参数。因此,不能通过右值参数调用 reference_wrapper:

std::tr1::ref(obj)(42);

改为:

int arg = 42;
std::tr1::ref(obj)(arg);

工作得很好。

std::tr1::bind( std::tr1::ref(obj), 42 )() 

之所以有效,是因为 bind 通过复制获取参数。

关于c++ - 关于 reference_wrapper 和可调用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2840541/

相关文章:

c++ - Boost ASIO 阻塞回调

c++ - 如何使用 CUDA 驱动程序功能?

c++ - 不同指针类型之间的无效比较 : 'type*' and 'type&(*)()'

c++ - 正则表达式匹配

c++ - 访问嵌套对

c++ - 特征库中标准差的列初始化和计算

c++ - 使用 Boost::Spirit 从中缀到前缀的 n 元 bool 语法转换?

c++ - const 参数 vs const 引用参数

c++ - 在默认构造函数签名中返回对象与引用

c++ - 使用 C++ TR1 生成随机数