Boost logo

Boost Users :

From: Stuart Dootson (stuart.dootson_at_[hidden])
Date: 2005-04-30 04:54:37


On 4/30/05, Delfin Rojas <drojas_at_[hidden]> wrote:
> Hello all,
>
> I hope somebody can help me with this. What I want to do is the following:
>
> Let's say I have a templated class called Foo
>
> template<class U>
> class Foo
> {
> public:
> Foo(U * p) : m_p(p) {}
> ~Foo() {}
> U* getP() const { return m_p; }
> private:
> U* m_p;
> };
>
> Now let's say I want to have a collection of pointers to Foo. What should I
> do? The possibilities I can think of are the following:
>
> 1) Create a class FooBase and have Foo inherit from FooBase. FooBase is
> non-templated so there should be no problem with having a collection of
> pointers to FooBase where I can put instances of Foo. The problem with this
> approach is that given a FooBase* in that collection I could not use the
> getP method because I would not know what type of Foo it holds.
>
> 2) Create a boost::variant of all the possible types of Foo<U>* I want to
> have. Then have a collection of this FooVariant. Using static visitation I
> can obtain the original type of Foo<U>* in a given FooVariant. The problem
> with this approach is that I get an ICE from VC++ 7.1 when the type of U
> gets too complex (shared_ptr to another type for example).
>
> Have I overlooked something? Is there a better technique for what I want to
> achieve? Any help would be great,
>
> Thanks
>
> Delfin Rojas
>

Using the first method, you could use something like this:

class FooBase
{
public:
   template<class T>
   T* getP() const { return IsSameType(typeid(T*))?(T*)RawPointer():(T*)0; }
private:
   virtual bool IsSameType(std::type_info const& ti) const = 0;
   virtual void* RawPointer() const = 0;
};

template<class U>
class Foo : public FooBase
{
public:
   Foo(U * p) : m_p(p) {}
   ~Foo() {}
private:
   U* m_p;
   virtual bool IsSameType(std::type_info const& ti) const { return
0!=(ti == typeid(U*)); }
   virtual void* RawPointer() const { return (void*)m_p; }
};

In the following fragment

   Foo<int> blah(new int);

   int* pInt = blah.getP<int>();
   char* pChar = blah.getP<char>();

pInt is non-zero, pChar is zero because char != int.

Stuart Dootson


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net