Is it possible and how to call a templated member function of a class using std::async (preferably without using 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.
#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:
I'd suggest the same thing as Axalo in the comments above, you can solve the compile error by casting.
#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 .
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:
static_cast<void(X::*)(int)>(&X::member_template<int>)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.