std thread call template member function of template class: compiler error

后端 未结 2 391

Here is the code. It does not compile in vs2013, but does compile in gcc4.8

error C2665: \'std::thread::thread\' : none of the 4 overloads could convert all the argu

2条回答
  •  梦毁少年i
    2021-01-20 06:11

    There is another way you can achieve above problem,If you would mind ! First just look explicit constructor of thread object:

    template< class Function, class... Args > 
    explicit thread( Function&& f, Args&&... args );
    

    f - Universal reference for function object.

    args - variadic arguments for function(functor) f.

    (I am not going to explain deeper and deeper about variadic calling used here). So now we know we can deal with functors therefore, Define a functor(function object) like below :

    template
    class TestClass
    {
    public:
        TestClass(){};
        ~TestClass(){};
    
        T  t;
    
        template
        void operator()(U u1,U u2){
            std::cout << "fun: " << u1*u2 << '\n';
        }
    
    };
    int main()
    {
        TestClass  A;
        auto aaa = std::thread(A,1,100);// calling functor A(1,100)
        aaa.join()
        //or if you can move object from main thread to manually created thread aaa ,it's more elegant.
        auto aa = std::thread(std::move(A),1,100);
        aa.join();
        A(1, 99);
        system("Pause");
        return 0;
    }
    

    //Please notice here I've not used any locker guard system. If you use static function you don't have to bind respective instance each time this may change your expected run-time behavior therefore you have to managed,

     template
        static void fun(U u)
        {
            std::cout << "fun: " << u << '\n';
        }
    then invoke the function,
    int main()
    {
        TestClass  A;
        auto aaa = std::thread(&TestClass::fun, 1);
        system("Pause");
        return 0;
    }
    

提交回复
热议问题