简体   繁体   English

用std :: async调用模板成员函数

[英]Call a templated member function with std::async

Is it possible and how to call a templated member function of a class using std::async (preferably without using std::bind)? 是否有可能以及如何使用std :: async(最好不使用std :: bind)调用类的模板化成员函数? Please explain if C++11 or C++14 standard allows such a call in general and how to make it work in MSVS2013 in particular. 请说明C ++ 11或C ++ 14标准通常是否允许此类调用,以及如何使其在MSVS2013中特别有效。

#include <future>

template<typename T> void non_member_template(T val) {}

struct X
{
    void member_non_template(int val) {}
    template<typename T> void member_template(T val) {}
    void call()
    {
        int val = 123;
        std::async(std::launch::async, &non_member_template<int>, val); // ok
        std::async(std::launch::async, &X::member_non_template, this, val); // ok
        std::async(std::launch::async, &X::member_template<int>, this, val); // error
    }
};

int main()
{
    X x;
    x.call();
}

I have never seen code break a compiler before, but here you go: 我以前从未见过代码会破坏编译器,但您可以执行以下操作:

错误MSB6006:“ CL.exe”退出,代码为1

I'd suggest the same thing as Axalo in the comments above, you can solve the compile error by casting. 我在上面的评论中建议与Axalo相同,您可以通过强制转换解决编译错误。

#include <future>

template<typename T> void non_member_template( T val ) {}

struct X
{
    void member_non_template( int val ) {}
    template<typename T> void member_template( T val ) {}
    void call()
    {
        int val = 123;
        std::async( std::launch::async,  &non_member_template<int>, val ); // ok
        std::async( std::launch::async, &X::member_non_template, this, val ); // ok
        //std::async( std::launch::async, &X::member_template<int>, this, val ); // error
        std::async( std::launch::async, static_cast< void ( X::* )( int )>( &X::member_template<int> ), this, val ); // ok
    }
};

int main()
{
    X x;
    x.call();
}

Apparently it was a bug in Microsoft Visual C++ 2013 and 2015 Preview which is going to be fixed in the future version of Visual C++: Passing member template function to std::async produces compilation error . 显然,这是Microsoft Visual C ++ 2013和2015 Preview中的一个错误,该错误将在Visual C ++的未来版本中修复:将成员模板函数传递给std :: async会产生编译错误

So the example program is valid C++ code and if you need a workaround for Visual C++ 2013 use a cast in the last call to std::async as suggested in the comments: 因此,示例程序是有效的C ++代码,如果您需要Visual C ++ 2013的变通办法,请在注释的建议中,在最后一次调用std::async

static_cast<void(X::*)(int)>(&X::member_template<int>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM