Ragnar
Ragnar

Reputation: 103

Doing type erasure safely without boost and c++0x

Say i have a templated class

template<class T>
class A;

template<>
class A<int>
{
    public:
         void print(){ std::cout << "I am an int !" << std::endl; }
};

template<>
class A<double>
{
    public:
         void print(){ std::cout << "I am a double !" << std::endl; }
};

Now, if I want to store every possible instance of A in the same container, say a vector.

Then the classic (and only way I know) is to make another class A_base with a pure virtual print() member function, and to stores pointer to A_base initialized to instances of A. Doing it with new may provoke memory leaks and/or exception unsafety, so a reasonable way to solve this problem would be to use boost::shared_ptr or std::tr1::shared_ptr, because copying std::auto_ptr may lead to ownership issues and undefined behavior !

Is there any way of doing type erasure without including boost or c++0x dependancies? :)

Thanks !

Upvotes: 3

Views: 251

Answers (2)

Puppy
Puppy

Reputation: 146910

The only answer to this question is "Roll your own class that already exists in Boost", whether you like ptr_vector, shared_ptr, any, etc. They already have all the bases covered in this regard. Pick your favourite and roll your own implementation, then use that.

Edit: A commenter mentioned TR1. Good shout. TR1 has shared_ptr in it.

Upvotes: 3

J&#246;rgen Sigvardsson
J&#246;rgen Sigvardsson

Reputation: 4887

Take a look at boost/any.hpp. I did.

Upvotes: 1

Related Questions