Let's say I have some class:
class A {};
class B {};
...
I want to implement a function as:
auto cs[2] = {A, B};
for(int i=0; i<2; i )
{
auto ob = new cs[i];
}
Is it possible?
If it is impossible, is the following code possible?
auto cs[2] = {"A", "B"};
for(int i=0; i<2; i )
{
auto ob = new stringToClass(cs[i]);
}
What should stringToClass
be?
Any suggestion is appreciated~~~
Update
Sorry for this unclearing question. The reason why I ask this question is because that I need to new many class. Just like:
auto a = new A;
auto b = new B;
...
Thus, I want to new these class by for-loop
.
CodePudding user response:
It is not clear what you are actually trying to do, but it is not possible to have a loop where each iteration resolves auto
to different types. But if your only purpose is to call constructors of several types where the types should be provided as an "array-like structure", you may use template metaprogramming (e.g. you may want to warm up the cache). For example:
template<typename C>
auto createClass() {
return std::make_unique<C>();
}
template<typename T>
struct Creator {
static void createClasses() { }
};
template<typename C, typename... Cs>
struct Creator<tuple<C, Cs...>> {
static void createClasses() {
createClass<C>();
Creator<tuple<Cs...>>::createClasses();
}
};
The createClass()
template function creates an instance of the class, and Creator::createClasses creates many classes based on the type of the tuple:
struct A {
A() { std::cout << "A::A()" << std::endl; }
};
struct B {
B() { std::cout << "B::B()" << std::endl; }
};
using Classes = std::tuple<A, B>;
int main()
{
Creator<Classes>::createClasses();
return 0;
}
the output is:
A::A()
B::B()
As you may noticed, the createClass()
function returns an unique_ptr
, and the created classes are destroyed immediately. That is up to you to figure out what to do with that.
CodePudding user response:
I want to new these class by for-loop
It's Not Possible in c
template <class T>
void AllocateMemoryInHeap () {
T obj = new T ();
return obj;
}
// Usage :
std::vector <type_t> types; // Err : it's not possible to store types in array
for (int i = 0 ; i < 100 ; i )
auto anyVar = AllocateMemoryInHeap <types[i]> ();