Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将成员函数传递给模板函数_C++_C++11 - Fatal编程技术网

C++ 将成员函数传递给模板函数

C++ 将成员函数传递给模板函数,c++,c++11,C++,C++11,鉴于以下功能: template<class F, class... Args> auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args..

鉴于以下功能:

template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) 
    -> std::future<typename std::result_of<F(Args...)>::type>
{
    using return_type = typename std::result_of<F(Args...)>::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> res = task->get_future();
    return res;
}
其功能是:

foo.do_something();

我曾尝试使用
std::bind
std::mem_fn
带或不带“&”,但都失败了。

除了@IgorTandetnik在评论中提到的内容外,您还可以使用
std::bind
std::mem_fn
将成员函数传递给您的方法:

struct Foo
{
   void do_something() {}
   void do_something_else(int x, int y, std::string str) {}
};

int main()
{
   Foo foo;
   ThreadPool pool;

   auto func_sth = std::bind(std::mem_fn(&Foo::do_something), foo);
   auto func_sth_else = std::bind(std::mem_fn(&Foo::do_something_else), foo, 10 , 11, "hi");

   pool.enqueue(func_sth);
   pool.enqueue(func_sth_else);

   return 0;
}

尝试
pool.enqueue([foo](){foo.do_something();})您是否尝试过:pool.enqueue([foo]{foo.do_something();})?与其说您“尝试过绑定和mem_fun”,不如告诉我们您尝试过的代码。对于非重载非模板函数,您也可以使用
pool.enqueue(&foo::do_something,&foo,其他参数to_do_something…)
。如果do_something接受参数,正确的语法是什么,比如说两个整数?@BulGali我用一些参数更新了一个函数的答案。出于某种原因,我得到了:/functional:467:70:错误:调用'std::tuple'时没有匹配的函数。知道为什么会这样吗?如果参数通过引用传递,是否有特殊语法?说“std::string&str”@BulGali如果您要通过引用传递一个参数(例如,
str
),则使用
std::ref(str)
传递该参数。对于常量引用参数,可以改用
std::cref()
struct Foo
{
   void do_something() {}
   void do_something_else(int x, int y, std::string str) {}
};

int main()
{
   Foo foo;
   ThreadPool pool;

   auto func_sth = std::bind(std::mem_fn(&Foo::do_something), foo);
   auto func_sth_else = std::bind(std::mem_fn(&Foo::do_something_else), foo, 10 , 11, "hi");

   pool.enqueue(func_sth);
   pool.enqueue(func_sth_else);

   return 0;
}