Answer the question
In order to leave comments, you need to log in
How to write an interface and implementation of a template class in c++?
Comrades, good day!
Today I spent quite a lot of time, and did not understand how this can be done.
I want to figure out how to write separately (interface and implementation) template classes in c++.
For example, based on std queue and mutex, I want to make a blocking queue, but I don’t know what objects I will have to use in development.
I declare an interface:
#ifndef QUEUE_BLOCK_T_HPP
#define QUEUE_BLOCK_T_HPP
#include <queue>
#include <mutex>
template <class T>
class block_queue{
public:
block_queue(int = 100); // default size
~block_queue();
void push(const T&);
private:
std::mutex lock;
std::queue<T> q;
int max_size;
};
#endif
#include "queue_block_t.hpp"
template <class T>
block_queue<T>::block_queue(int max_size_) : max_size(max_size_){}
template <class T>
block_queue<T>::~block_queue(){}
template <class T>
void block_queue<T>::push(const T& elem){
lock.lock();
q.push(elem);
lock.unlock();
}
#include "queue_block_t.hpp"
int main(int argc, char **argv) {
block_queue<int> q(500);
q.push(10);
return 0;
}
main.cpp:7: undefined reference to `block_queue<int>::block_queue(int)'
main.cpp:8: undefined reference to `block_queue<int>::push(int const&)'
main.cpp:7: undefined reference to `block_queue<int>::~block_queue()'
main.cpp:7: undefined reference to `block_queue<int>::~block_queue()'
#ifndef QUEUE_BLOCK_T_HPP
#define QUEUE_BLOCK_T_HPP
#include <iostream>
#include <queue>
#include <mutex>
template <class T>
class block_queue{
public:
block_queue(int max_size__ = 100) : max_size(max_size__) { }
~block_queue(){ }
void push(const T& elem){
lock.lock();
q.push(elem);
lock.unlock();
}
private:
std::mutex lock;
std::queue<T> q;
int max_size;
};
#endif
Answer the question
In order to leave comments, you need to log in
you cannot separate the header and the implementation of the template class, this is impossible
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question