Reputation: 1
the question says: define a container (possibly a template) of action objects (will be named Runner). Action Objects (AO) are objects that perform a user supplied function. The idea is that once an action container is loaded with AOs it can be asked to run or execute them. The results of the execution are returned in a Results array. example:
AO a1(mul, x, x); //if run method is called it returns x*x
AO a2(add, y, 1); //if run method is called it returns y+1
AO a3(print, s); //if run method is called it prints s on cout
Runner<AO> r = {a1,a2,a3};
so now int the runner class how should I implement a constructor that takes the constant array and knows it size
template<typename a>
class runner{
a* m;
int size;
public:
runner(const a x[]){
//how to know the size of x[] to initialize m=new a[size] and then fill it with a1,a2,a3 ??
}
Upvotes: 0
Views: 101
Reputation: 61
What u can do is push all the objects in a vector and then pass it in Ctor.
Follow these Steps :
Include:
#include<vector>
In main():
Declare objects of class AO
and push them to vector<AO> x
AO a1(mul, x, x); //if run method is called it returns x*x
AO a2(add, y, 1); //if run method is called it returns y+1
AO a3(print, s);
vector<AO> x;
x.push_back(a1);
x.push_back(a2);
x.push_back(a3);
Runner<AO> r(x);
Modify the template class
class Runner{
a* m;
int size;
public:
Runner(vector<a> x)
{
m = new a[x.size()];
for (int i = 0; i < x.size(); i++)
{
m[i] = x.at(i);
}
}
};
Hope this is actually what u want
Upvotes: 0
Reputation: 122
An array can not know it's size and thus you should pass it as an argument to the constructor.
Even simpler: Use std::vector
. With the handy std::initializer_list
you can keep initializing your objects with the brace initializers {}
. Here an example:
#include <iostream>
#include <vector>
#include <initializer_list>
template<typename a>
class runner{
private:
std::vector<a> objects;
public:
runner(std::initializer_list<a> init) {
objects.insert(objects.end(), init.begin(), init.end());
}
void iterate() {
for(auto obj : objects)
std::cout << obj << std::endl;
}
};
int main() {
//As template type I've chosen int, you can choose your own class AO aswell
//This calls the constructor with the std::initializer_list
runner<int> test = {1,2,3,4,7,0};
test.iterate();
return 0;
}
Upvotes: 1