c++ - Can a member function be used anywhere a free function can using std::function? -


i have code (courtesy of progschj on github) have adapted exemplify question. maketask moves function , arguments maketask makes packaged_task. created task executed whereupon future returned caller. slick, able member function well. if put func struct, f&& in maketask fails errors noted in code.

#include <future> #include <memory> #include <string> #include <functional>  template<class f, class... args> auto maketask( f&& f, args&&... args )-> std::future< typename std::result_of< f( args... ) >::type > {   typedef typename std::result_of< f( args... ) >::type return_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 > resultfuture = task->get_future();    ( *task )( );    return resultfuture; }  struct {   int func( int nn, std::string str )   {     return str.length();   } };  int main() {   // error c2893: failed specialize function template 'std::future<std::result_of<_fty(_args...)>::type> maketask(f &&,args &&...)'   // note: 'f=int (__thiscall a::* )(int,std::string)'   // note: 'args={int, const char (&)[4]}'   auto resultfuture = maketask( &a::func, 33, "bbb" );  // not compile    int nn = resultfuture.get();    return 0; } 

i can make work if turn func static, break other parts of app code.

edit1: figured out syntax std::function , modified sample new error messages. maketask’s f&& move argument doesn’t accept afunc callable object.

edit2: because of barry's answer, change sample code original posting answer makes sense future viewers.

&a::func non-static member function, means needs instance of a operate in. convention function objects/adapters use 1st argument provided instance.

maketask() requires first argument (f) invoke-able other arguments (args...). &a::func requires three arguments: object of type a (or pointer a or reference_wrapper<a>), int, , string. you're missing first one:

auto resultfuture = maketask( &a::func, a{}, 33, "bbb" );                                        ^^^^^ 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -