简体   繁体   中英

How to create a template class with a constructor (with parameters) and pass a method of the class to a thread

I want to create a template class that incapsulate a vector. The constructor of the class receive an int size as parameter. In the class there's a method to push an element into the vector. In the main I want to pass this push() to a thread

#include <iostream>
#include <thread>
#include <vector>
using namespace std;

template <class T> class Queue{
private:
int size;
vector<T> v;
public:
Queue(int size) {
    this->size = size;
}

void push(T t) {
    v.push_back(t);
 }
};

int main()
{
Queue<int> * miaCoda = new Queue(4);
thread t1(&Queue::push, miaCoda, 2);
t1.join();
}

I get all this error in the first 2 lines of the main

Error C2514 'Queue': class has no constructors Error C2955 'Queue': use of class template requires template argument list
Error C2661 'std::thread::thread': no overloaded function takes 3 arguments Error (active) E0441 argument list for class template "Queue" is missing
Error (active) E0289 no instance of constructor "std::thread::thread" matches the argument list

Queue<int> * miaCoda = new Queue(4);
thread t1(&Queue::push, miaCoda, 2);

Queue is not a class. It is a template. What is a class, here, is Queue<int> . Now that's a class, with full rights and privileges thereof.

It follows that to get a pointer to a class method, well, you have to specify the class whose method you need to get a pointer to:

thread t1(&Queue<int>::push, miaCoda, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM