繁体   English   中英

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

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

是否有可能以及如何使用std :: async(最好不使用std :: bind)调用类的模板化成员函数? 请说明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();
}

我以前从未见过代码会破坏编译器,但您可以执行以下操作:

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

我在上面的评论中建议与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();
}

显然,这是Microsoft Visual C ++ 2013和2015 Preview中的一个错误,该错误将在Visual C ++的未来版本中修复:将成员模板函数传递给std :: async会产生编译错误

因此,示例程序是有效的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