조재훈
조재훈

Reputation: 1

How can I use template class as parameters of function?

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.

Upvotes: 0

Views: 77

Answers (2)

Wander3r
Wander3r

Reputation: 1881

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;
}

Upvotes: 1

robthebloke
robthebloke

Reputation: 9672

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)

Upvotes: 3

Related Questions