在抽象基类中使用C++ 11的std :: async

问题描述:

为什么不让这样的线程在抽象基类中工作?我试图抽象出从这个基类派生的用户的所有多线程细节。当我明确写出callbackSquare返回类型int时,我不明白它为什么说“没有类型命名为'type'”。在抽象基类中使用C++ 11的std :: async

#include <iostream> 
#include <future> 
#include <vector> 

class ABC{ 
public: 
    std::vector<std::future<int> > m_results; 
    ABC(){}; 
    ~ABC(){}; 
    virtual int callbackSquare(int& a) = 0; 
    void doStuffWithCallBack(); 
}; 

void ABC::doStuffWithCallBack(){ 
    for(int i = 0; i < 10; ++i) 
     m_results.push_back(std::async(&ABC::callbackSquare, this, i)); 

    for(int j = 0; j < 10; ++j) 
     std::cout << m_results[j].get() << "\n"; 
} 

class Derived : public ABC { 
    Derived() : ABC() {}; 
    ~Derived(){}; 
    int callbackSquare(int& a) {return a * a;}; 
}; 

int main(int argc, char **argv) 
{ 

    std::cout << "testing\n"; 

    return 0; 
} 

奇怪的错误,我越来越有:

/usr/include/c++/5/future:1709:67: required from 'std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...) [with _Fn = int (ABC::*)(int&); _Args = {ABC*, int&}; typename std::result_of<_Functor(_ArgTypes ...)>::type = int]' 
/usr/include/c++/5/future:1725:19: required from 'std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(_Fn&&, _Args&& ...) [with _Fn = int (ABC::*)(int&); _Args = {ABC*, int&}; typename std::result_of<_Functor(_ArgTypes ...)>::type = int]' 
/home/taylor/Documents/ssmworkspace/callbacktest/main.cpp:16:69: required from here 
/usr/include/c++/5/functional:1505:61: error: no type named 'type' in 'class std::result_of<std::_Mem_fn<int (ABC::*)(int&)>(ABC*, int)>' 
     typedef typename result_of<_Callable(_Args...)>::type result_type; 
                  ^
/usr/include/c++/5/functional:1526:9: error: no type named 'type' in 'class std::result_of<std::_Mem_fn<int (ABC::*)(int&)>(ABC*, int)>' 
     _M_invoke(_Index_tuple<_Indices...>) 
+0

“'callbackSquare(int&a)'”是否有通过ref传递的原因? – curiousguy

+0

[通过引用将参数传递给std :: async失败](https://stackoverflow.com/questions/18359864/passing-arguments-to-stdasync-by-reference-fails) – Rakete1111

+0

@curiousguy不是真的这样例。但最终我会传递更大的论据。 – Taylor

你的问题可以用一个接受任何引用功能被复制:

#include <future> 

int f(int& a) 
{ 
    return a * a; 
} 

int main() 
{ 
    int i = 42; 
    auto r = std::async(f, i); 
} 

接受在你的代码一提的是因为变量将被循环迭代修改为,因为被调用的函数也访问该变量,所以创建数据竞争。

更改函数以接受输入参数的值,或者如果您承认风险,则通过std::ref(i)std::cref(i)(如果函数接受const引用)调用std::async