Template function will not compile when called as a thread

前端 未结 4 733
暗喜
暗喜 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:35

    Your missing the argument list of your template.

    Try:

     unsigned int counter = 100;
     thread one(Threader<unsigned int>,counter);
    

    or, if you are using c++x0/c++11 standard, give your template a standard type like:

    template <typename TYPE_size = unsigned int>
    void Threader(TYPE_size counter)
    {
        counter++;
    }
    int main()
    {
        unsigned int counter = 100;
        thread one(Threader<>,counter);
        one.join();    
        cout << counter;
    }
    
    0 讨论(0)
  • 2021-01-04 20:46

    There is no function named Threader. When you write Threader<int> or something, then the compiler creates a function. If you then write Threader<float>, then the compiler creates a new function. You can either provide a default template parameter, or give it a parameter when you call it.

    template <class TYPE_size=int>
    

    or

    thread one(Threader<int>, counter);
    
    0 讨论(0)
  • 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 <iostream>
    #include <thread>
    template <class T>
    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.

    0 讨论(0)
  • 2021-01-04 20:59

    I'm taking the liberty of offering a variety of fixes to achieve what I believe is intended behaviour:

    #include <thread>
    
    template <typename T>
    void Threader(T & counter)    // take by reference!
    {
       counter++;
    }
    
    int main()
    {
       unsigned int counter = 100;
       std::thread one(Threader<unsigned int>,   // specify template *instance*
                       std::ref(counter) );      // pass variable as reference
       one.join();
       return counter;
    }
    
    0 讨论(0)
提交回复
热议问题