This topic is now archived and is closed to further replies.


templates and dynamic_cast ?

Recommended Posts

Hey guys! I'm having a problem with casting a templated type, looks like this:
//This is just a base class

//Need this, otherwise the compiler complains at compiletime...

class ModuleIDBase {
	ModuleIDBase() {

	~ModuleIDBase() {

//This is the actual module ID

//The purpose is to let the user choose what type

//of ID the module will have

//the important function is the T GetID()

//which returns the id of this module

template <class T>
class ModuleID : public ModuleIDBase {
	ModuleID(T id) {
		m_moduleID = id;

	~ModuleID() {

	T GetID() {
		return m_moduleID;
	T m_moduleID;

//Now I have a std::vector where I store all the moduleID's

//as a ModuleIDBase

std::vector<ModuleIDBase*> m_vecModuleIDs;

//Now I create a new ModuleID consisting of a string type (const char*) and add it to the vector:

ModuleID<const char*>* rendererID = new ModuleID<const char*>("GL_RENDERER");

//Here comes the problem. I have a Templated function taking a parameter T. This function retrieves a Module for me by checking

//the ModuleID consisting of the given type T!

template <class T>
Module* getModule(T id) {
	ModuleID<T> moduleID(id);
	//Just for testing purpose I know that the CORRECT moduleID is the first one

	//in the vector...

	ModuleIDBase* pModuleId = *(m_vecModuleIDs.begin());

	//Now here is the tricky thing, where I want to convert the ModuleIDBase* pointer to

	//a correct ModuleID with the correct type T. If the ModuleID stored in this

	//first item in the vector is of type T, then the conversion should be OK !?

	ModuleID<T>* tmpModuleID = dynamic_cast< ModuleID<T>* >(pModuleId);  

	return new Module;

//And here is how I call the function:

//Since I give a const char* as the parameter... the 

//function will try to dynamic_cast the ModuleIDBase* to a ModuleID<const char*>, which is exactly what I created and pushed to the vector!

//Thish should mean that the dynamic_cast should succede right!?

But the problem is that the compiler complains about the dynamic_cast: dynamic_cast: ModuleIDBase is not a polymorphic type Does anyone know what to do about this? thank you guys! [edited by - bilsa on April 5, 2004 9:24:20 AM]

Share this post

Link to post
Share on other sites
Hello bilsa,

I believe what you need is a virtual method in your derived class (ie templated class), but I think templates can't have virtual methods.

The dymanic_cast uses the virtual function table to do the casting checks needed.
And since the derived class is a template and not a ture polymorphic type, it can't do the cast

Lord Bart

Look at Pure virtual templated member function

[edited by - lord bart on April 5, 2004 9:32:47 AM]

Share this post

Link to post
Share on other sites