Although this question is old, I would like to discover a way to do this. (Not quite sure about portability)
From what I understand, you have class B and C that inherit from some class A , and there is only one virtual function between them. (The method presented here works if B and C also not connected.)
class A { public: virtual std::string hello() = 0; }; class B : public A { public: virtual std::string hello() { return "B"; } }; class C : public A { public: virtual std::string hello() { return "C"; } };
And then you want to take B to C and then call hello and get "B" .
Thus, there is a way to create an flooded version of boost::any that will bring anything if it suits :)
struct parent {}; template< typename T > struct child : public parent { child(T const& t): item(t){} mutable T item; }; template< typename T > T& as(parent const & p) { return static_cast< child< T > const& >(p).item; }
Then mix everything together:
B b; parent* p = new child< B >(b); std::cout << as< C >(*p).hello() << std::endl;
You can see the code in action here .
To take another step, we can create a function that converts from one type to another without providing the back end of the mosquito about what happens between them.
template< typename TO, typename FROM > TO& convert(FROM const& from) { parent* p = new child< FROM >(from); return as< TO >(p); };
It can be run here .
(I realized that I skipped inheritance in these code link examples, but after reading the question, I think it was really desirable. So, to see the test without inheritance, go here )
Some other code that I started playing with something that I thought could help too ...
#include <iostream> #include <string> class B { public: virtual char hello() {return 'B';} }; class C { public: virtual int hello() {return 65;} }; struct parent {}; template< typename T > struct child : public parent { child(T const& t): item(t){} mutable T item; }; template< typename T > T& as(parent const & p) { return static_cast< child< T > const& >(p).item; } template< typename TO, typename FROM > TO& convert(FROM const& from) { parent* p = new child< FROM >(from); return as< TO >(*p); }; int main() { B b; std::cout << convert< C, B >(b).hello() << std::endl; C c; std::cout << convert< B, C >(c).hello() << std::endl; } // ==== OUTPUT ==== // 66 // A
Figured out how to do it all inside the conversion function:
template< typename TO, typename FROM > TO& convert(FROM const& from) { struct parent {}; struct child : public parent { child(FROM const& t): item(t){} mutable FROM item; }; struct sibling : public parent { sibling(TO const& t): item(t){} mutable TO item; }; parent* p = new child(from); return static_cast< sibling const& >(*p).item; };