Sign in to follow this  
AcidKor

C++ template and polymorphism

Recommended Posts

Hi I'am looking for a code patern who allow to use a template class without knowing his type. Here a sample code of what I want to do :


template <class type> class KeyFrame
{
  public:
    tfloat m_Time;
    type   m_Value;

    KeyFrame()
    {
    }
};


template <class type> class KeyFrameTrack 
{
  public:
  tarray<KeyFrame<type> > keyFrameList;

  tvoid AddKey(tfloat time, type  keyValue)
  {
    keyFrameList.PushBack(KeyFrame<type>(time, keyValue));
  }
};

class Animation
{
  public:
    tarray<KeyFrameTrack *> trackList;
};

//....
//Later I want to do :
KeyFrameTrack<tfloat> track1;
KeyFrameTrack<tfloat> track2;

Animation anim1;

anim1.trackList.PushBack(track1);
anim1.trackList.PushBack(track2);

anim1.trackList[0]->AddKey(1, 5.2f);
anim1.trackList[1]->AddKey(1, true);


I know that it doesn't work this way but is there any simple solution to do such things Thanks for any idea ! Jerome

Share this post


Link to post
Share on other sites
I question why some-body would really wont to do that meh anyways., from what i understood your trying to do you have these choices:

1. Use pointers void, no type safety, this is tricky to delete memory correctly.

2. Use boost:shared_ptr (smart pointer) to void, it's little bit more type safe, can delete the memory correctly for you.

3. Use inheritance and boost::shared_ptr to base type, this is just faking a heterogeneous container and make alot of unrelated types inherit from some none-sense common base.

4. Use boost::any.

As you can see from numenous references to boost i suggest you download that library, here is one way you could do what your trying to achieve:


#include <boost\any.hpp>
#include <boost\pool\pool_alloc.hpp>
#include <boost\smart_ptr.hpp>
#include <vector>

struct key_frame {

float time;
boost::any value;

key_frame(float t = 0.0f)
: value(), time(t) {}

template < typename Type >
key_frame(const Type& val,
float t = 0.0f)
: value(val), time(t) {}
};

struct keyframe_track {

typedef std::vector< key_frame > keyframe_list;

keyframe_list keyframes;

template < typename Type >
void add_key(float time, const Type& keyValue) {
keyframes.push_back(key_frame(time, keyValue));
}
};

struct animation {

typedef boost::shared_ptr<keyframe_track> track_ptr;
typedef boost::fast_pool_allocator<track_ptr> track_alloc;
typedef std::vector<track_ptr, track_alloc> track_list;

track_list tlist;

};

int main() {

animation a;
animation::track_ptr kft(new keyframe_track);

kft->add_key(1, 5.2f);
kft->add_key(1, true);
a.tlist.push_back(kft);
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this