Template function will not compile when called as a thread

前端 未结 4 734
暗喜
暗喜 2021-01-04 20:22

I have a problem relating to template functions and threads:

template 
void Threader(TYPE_size counter)
{
    counter++;
}
int main()
         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 20:52

    C++11 introduced lambdas, this can be used in this case as well.

    Basically, the thread is created with the use of a lambda, where the lambda calls the function that then allows template type deduction to take place.

    thread one([counter]() { Threader(counter); });
    

    Above, the counter is captured by value, but as some of the answer suggest, a capture by reference can also be used

    #include 
    #include 
    template 
    void Threader(T& counter)
    {
        counter++;
    }
    int main()
    {
        unsigned int counter = 100;
        std::thread one([&counter]() { Threader(counter); });
        one.join();    
        std::cout << counter;
    }
    

    Note: this question was flagged as a duplicate, hence the addition with the use of newer language features.

提交回复
热议问题