jeudi 29 décembre 2016

using decltype(*this) to refer to the current class method

I try to compile the following code and receive error:

test.cpp: In member function ‘void CObj::run()’:
test.cpp:19:39: error: ‘th_func’ is not a member of ‘std::remove_reference<CObj&>’
    thread_pool.push_back(std::thread(&std::remove_reference<decltype(*this)>::th_func,this,th_index));
                                       ^

I try to pass the pointer to a class method from another method of the current class and the compiler tells me that th_func is not a member of the given type. How can I fix this code?

#include <iostream>
#include <vector>
#include <thread>

class CObj
{
public:

    void th_func(int i)
    {
        std::cout<<"Hello from thread ("<<i<<")."<<std::endl;
    }

    void run()
    {
        int N_threads=4;
        std::vector<std::thread> thread_pool;
        for(int th_index=0;th_index<N_threads;th_index++)
            thread_pool.push_back(std::thread(&std::remove_reference<decltype(*this)>::th_func,this,th_index));
        // wait for tasks to finish
        for(std::thread& th : thread_pool)
            th.join();

    }
};

int main()
{
    CObj obj;
    obj.run();
}

Aucun commentaire:

Enregistrer un commentaire