-----Original Message----- From: boost-users-bounces@lists.boost.org [mailto:boost-users- bounces@lists.boost.org] On Behalf Of Stuart Dootson Sent: Saturday, April 30, 2005 2:55 AM To: boost-users@lists.boost.org Subject: Re: [Boost-users] How to get type given pointer to base?
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
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
On 4/30/05, Delfin Rojas
wrote: this 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
Yes, that would _work_ but unfortunately the code that need to call getP would have to call it with every possible type and check if the return is zero. Ideally I would like the following: FooBase * pB = new Foo<int>(new int); ... int * pI = pB->getP(); //compiles char * pChar = pB->getP(); //does not compile -delfin
_______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users