dimanche 30 mai 2021

c++11 template class return type

a simple class

   struct Test{
        void display(int x)
        {
           printf("%d\n", x);
        }
    };

c++11

template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<decltype(f(args...))>{

    auto task = std::make_shared<std::packaged_task<decltype(f(args...)())>>(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );
    return task->get_future();
}

call it just use (cls is the object of the class of the template function above)

Test test;
cls->enqueue(&Test::display, &test, 0);

the comipler error

candidate template ignored: substitution failure 
[with F = void (TestMem::*)(int), Rest = <TestMem *, int>]: called object type 'void (TestMem::*)(int)' is not a function or function pointer
        auto enqueue(F && f, Rest&&... rest) ->std::future<decltype(f(rest...))> {

above works well on a non class member function, can some one give a fix on c++11

c++14 works fine, but my project needs c++11

template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) {

    using return_type = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<return_type()>>(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );
    return task->get_future();
}

Aucun commentaire:

Enregistrer un commentaire