LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   c++ stl containers in classes (https://www.linuxquestions.org/questions/programming-9/c-stl-containers-in-classes-789191/)

tardigrade 02-15-2010 04:14 AM

c++ stl containers in classes
 
Is it possible to have a templated c++ stl container in another class without specifying the type prior to compile time? I haven't coded in c++ in a while and im at a total loss.

For example - Not real code. Just outlining the problem:
Code:


class HasAContainer{
 queue<ANY_TYPE> buffer
 HasAContainer(queue<ANY_TYPE> buffer){
  this.buffer = buffer
 }

main(){
 queue<int> buf1;
 HasAContainter one(b);
 queue<float> buf2;
 HasAContainer two(c)



}

irmin 02-15-2010 06:25 AM

Yes it is possible not to specify the type of the elements in the stl container. Just make your class to a template.

Code:

#include <queue>

template<typename T>
class HasAContainer {
 std::queue<T> buffer_;

public:
 HasAContainer(const std::queue<T>& buffer) : buffer_(buffer) { }
};

int main() {
 std::queue<int> buf1;
 HasAContainer<int> one(buf1);

 std::queue<float> buf2;
 HasAContainer<float> two(buf2);

 return 0;
}



All times are GMT -5. The time now is 07:45 PM.