I am in need of a template which can further create several templates (actually methods) such that dynamically a specific number of methods can be created, Below s the approach I have take and believe that there is no other way to achieve the same:
#include <iostream>
template<int i>
class loop {
public:
loop() { std::cout << "loop" << std::endl;
for (int index = 0 ; index < i ; index ++)
loop<1> x;
m[i] = x;
}
private:
loop<1>[i] m;
};
template<>
class loop<1> {
public:
loop() { std::cout << "loop 1" << std::endl; }
~loop() { std::cout << "des loop 1" << std::endl; }
void show(){ std::cout << "Hello" << std::endl; }
};
int main()
{
loop<10> l;
std::cout << "End" << std::endl;
}
Though I get a compile error but if I have below code:
#include <iostream>
template<int i>
class loop {
public:
loop() { std::cout << "loop" << std::endl;
//for (int index = 0 ; index < i ; index ++)
loop<i - 1> x;
//m[i] = x;
}
private:
//loop<1>[i] m;
};
template<>
class loop<1> {
public:
loop() { std::cout << "loop 1" << std::endl; }
~loop() { std::cout << "des loop 1" << std::endl; }
void show(){ std::cout << "Hello" << std::endl; }
};
int main()
{
loop<10> l;
std::cout << "End" << std::endl;
}
I get below output:
$ c++ -std=c++11 -g try35.cpp
$ ./a.exe
loop
loop
loop
loop
loop
loop
loop
loop
loop
loop 1
des loop 1
End
But this was perhaps not my requirement so:
#include <iostream>
template<int i>
class loop {
public:
loop() { std::cout << "loop" << std::endl;
for (int index = 0 ; index < i ; index ++)
loop<1> x;
//m[i] = x;
}
private:
//loop<1>[i] m;
};
template<>
class loop<1> {
public:
loop() { std::cout << "loop 1" << std::endl; }
~loop() { std::cout << "des loop 1" << std::endl; }
void show(){ std::cout << "Hello" << std::endl; }
};
int main()
{
loop<10> l;
std::cout << "End" << std::endl;
}
I believe was able to achieve the desired requirement:
$ c++ -std=c++11 -g try35.cpp
$ ./a.exe
loop
loop 1
des loop 1
loop 1
des loop 1
loop 1
des loop 1
loop 1
des loop 1
loop 1
des loop 1
loop 1
des loop 1
loop 1
des loop 1
loop 1
des loop 1
loop 1
des loop 1
loop 1
des loop 1
End
But then all instances are getting destructed and I am unable to find to store and the call each instance show method?
If I compile the code as shown in the beginning I get compile error:
try35.cpp:11:8: error: expected unqualified-id before '[' token
loop<1>[9] m;
^
try35.cpp: In constructor 'loop<i>::loop()':
try35.cpp:8:6: error: 'm' was not declared in this scope
m[i] = x;
^
try35.cpp:8:13: error: 'x' was not declared in this scope
m[i] = x;
^
Aucun commentaire:
Enregistrer un commentaire