可以在自由函数可以使用std :: function的任何地方使用成员函数吗?

时间:2016-07-15 19:40:24

标签: c++ std-function packaged-task

我有一些代码(由GitHub上的progschj提供),我已经调整了这个代码来举例说明我的问题。 MakeTask将任何函数及其参数移动到MakeTask中,后者生成一个packaged_task。执行创建的任务,然后将其未来返回给调用者。这很光滑,但我希望能够使用成员函数来做到这一点。但如果我把Func放入一个结构中,F&&在MakeTask失败,代码中记录了错误。

#include <future>
#include <memory>
#include <string>
#include <functional>

template<class F, class... Args>
auto MakeTask( F&& f, Args&&... args )-> std::future< typename std::result_of< F( Args... ) >::type >
{
  typedef typename std::result_of< F( Args... ) >::type return_type;

  auto task = std::make_shared< std::packaged_task< return_type() > >(
    std::bind( std::forward< F >( f ), std::forward< Args >( args )... )
    );

  std::future< return_type > resultFuture = task->get_future();

  ( *task )( );

  return resultFuture;
}

struct A
{
  int Func( int nn, std::string str )
  {
    return str.length();
  }
};

int main()
{
  // error C2893: Failed to specialize function template 'std::future<std::result_of<_Fty(_Args...)>::type> MakeTask(F &&,Args &&...)'
  // note: 'F=int (__thiscall A::* )(int,std::string)'
  // note: 'Args={int, const char (&)[4]}'
  auto resultFuture = MakeTask( &A::Func, 33, "bbb" );  // does not compile

  int nn = resultFuture.get();

  return 0;
}

如果我将Func转换为静态,我可以使它工作,但这将破坏我的应用程序代码的其他部分。

Edit1:我找到了std :: function的语法,并使用新的错误消息修改了示例。 MakeTask的F&amp;&amp; move参数不接受我的aFunc作为可调用对象。

Edit2:由于Barry的回答,我将示例代码更改回原始帖子,以便他的答案对未来的观众有意义。

1 个答案:

答案 0 :(得分:3)

&A::Func是一个非静态成员函数,这意味着它需要一个A的实例来操作。所有函数对象/适配器使用的约定是提供的第一个参数将是那个例子。

MakeTask()要求第一个参数(F)可以与所有其他参数(Args...)一起调用。 &A::Func需要三个参数:类型为A的对象(或指向Areference_wrapper<A>的指针),int,以及一个string。你只是错过了第一个:

auto resultFuture = MakeTask( &A::Func, A{}, 33, "bbb" );
                                       ^^^^^
相关问题