c++ - call member function of a vector of templated class -


i have templated class (btw, use templated class because gives huge performance gain):

template<int n> class a;

my first issue wanted make vector of it. people suggest using boost::any, use void*.

a<1> a0; a<2> a1; vector<void*> v; v.push_back(&a0); v.push_back(&a1);

the problem comes when want call member function of element of vector:

for(auto : v) (a*)a->foo();

of course, not work, because don't provide template argument during converstion.... but, don't find way make works.

do have idea?

a<1> , a<2> completely separate classes.

consider: if have 2 classes x , y both have foo method:

class x {public: void foo() {std::cout << "x::foo" << std::endl;}}; class y {public: void foo() {std::cout << "y::foo" << std::endl;}}; 

and vector of void*'s, how can call foo method on of them?

vector<void*> v; v.push_back(new x); v.push_back(new y); for(auto : v)     a->foo(); // how can this? 

the answer simple: you can't access member name this.

(what if made class z had foo method? you'd expect call if there z in vector; member names removed when code compiled, wouldn't know member called foo!)

however, create base class , make method virtual:

class xybase { public:     virtual void foo() = 0; } class x : public xybase {public: void foo() {std::cout << "x::foo" << std::endl;}}; class y : public xybase {public: void foo() {std::cout << "y::foo" << std::endl;}}; 

and can have vector<xybase*>:

vector<xybase*> v; v.push_back(new x); v.push_back(new y); for(auto : v)     a->foo(); // works! 

the template equivalent be:

class xbase { public:     virtual void foo() = 0; }  template<int n> class x : public xbase { public:     void foo() {         std::cout << "x<" << n << ">::foo" << std::endl;     } };  // ... later ...  vector<xbase*> v; v.push_back(new x<1>); v.push_back(new x<2>); for(auto : v)     a->foo(); // works! 

Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -