0

I want threading with template class parameter, but I don't know how I can use template class as parameter of thread method.

I already tried making method in template class, but I don't want it. People generally do not use this solution.

//....
//Linked List code
//.....


void func1(slist<T> s){
    for (int i = 0; i < 1000; i++) {
        s.push_(i);
    }
}                      // this part is problem of my code.

int main() {
    int i;
    slist<int> s;
    thread t1(func1,s); //Compile error.
        func1(s);   // here, too.

    return 0;
}

i expect the result that threads compete with Linked list.

Dean Seo
  • 5,486
  • 3
  • 30
  • 49
  • 1
    Make `func1` a function template and pass the template argument as part of the thread standup. – WhozCraig May 03 '19 at 05:54
  • 1
    You may need a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – L. F. May 03 '19 at 06:30

2 Answers2

3

The generic solution:

template<typename T>
void func1(slist<T>& s){
    for (int i = 0; i < 1000; i++) {
        s.push_(i);
    }
} 

Or you can specialise for one specific type:

void func1(slist<int>& s){
    for (int i = 0; i < 1000; i++) {
        s.push_(i);
    }
} 

(Also be aware that you probably want to pass a reference to the list, rather than a copy)

robthebloke
  • 9,331
  • 9
  • 12
1

As you want to make the thread accept a template, the function should be templated too.

template <typename T>
void func1(slist<T> s){        // most likely you need to pass by reference
    for (int i = 0; i < 1000; i++) {
        s.push_(i);
    }
}

While calling the function in main,

int main() {
    int i;
    slist<int> s;
    thread t1(func1<int>,s); //t1 needs to know which type it needs to instantiate of func1
    t1.join(); // let the thread finish

    return 0;
}
Wander3r
  • 1,801
  • 17
  • 27