Hello,

I have a class with template argument, MyClass. Next I initiate 3 copies of that templeate class with different types :

MyClass<char> mc1;
MyClass<int> mc2;
MyClass<float> mc3;

Is it possible in c++ to make a general pointer array with each element as reference to differenet initiated class?

MyClass *arr[3];
arr[0] = &mc1;
arr[1] = &mc2;
arr[2] = &mc3;

You can't do it the way your hoping to, but with some simple casting, it can be achived.

MyClass<char> mc1;
MyClass<int> mc2;
MyClass<float> mc3;

void *arr[3];
arr[0] = reinterpret_cast<void*>( &mc1 );
arr[1] = reinterpret_cast<void*>( &mc2 );
arr[2] = reinterpret_cast<void*>( &mc3 );

And, to then use an item from the array, you can do the following:

// void someFunction(MyClass<int>*)
someFunction( reinterpret_cast<MyClass<int>*>(arr[1]) );

Hope this helps :icon_lol:

1. You may assign any type object pointer to a void* pointer variable without explicit conversion - no need in reinterpret_cast:

void* pvoid[3];
pvoid[0] = &mc1; // or what else

2. It's possible but what for? All three variables mc1, mc2, mc3 have absolutely different types. Can you provide some loop examples where such void* pointer array elements are sensibly processed?

I have a class MyBaseClass

I want MyNewClass1, MyNewClass2, MyNewClass3 to inherit from MyBaseClass.

Next, I want to write a MyCreatorClass which I use to create MyNewClass instances and use them, I don't want to create a different MyCreatorClass for each MyNewClass so I try to do it with templates. Is this possible?

MyCreatorClass<MyNewClass1> mcc1;
MyCreatorClass<MyNewClass2> mcc2;
MyCreatorClass<MyNewClass3 > mcc3;

void *MyCreators[3];
MyCreators[0] = &mcc1;
MyCreators[1] = &mcc2;
MyCreators[2] = &mcc3;

int k;

cout >> "Enter selection between 0-2" >> endl;
cin << &k;


//here is the problem
(reinterpret_cast<MyCreatorClass>(MyCreators[k]))->Create();

Of course, it's possible but templates per se do not bear a relation to your problem. You want polymorphism: the most powerful concept of OOP implemented in C++. There are lots of articles and tutorials on this topic (and there are lots of DaniWeb solved threads).
For example, look at http://www.cplusplus.com/doc/tutorial/polymorphism.html
and/or http://www.softlookup.com/tutorial/c++/ch13.asp
In other words, you need an array of pointers to MyBaseClass, not void* pointers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.