Adding C++ template classes to a list -


I have a template class, c_fu & lt; T & gt; That is unique in many ways.

  straight Bar_Base {...}; Struct Bar_1: Public Bar_Base {...}; Struct Bar_2: Public Bar_Base {...}; Struct Bar_3: Public Bar_Base {...}; Class C_Foo & lt; T & gt; {...}; Category C_Foo_1: Public C_Foo & lt; Bar_1 & gt; {...}; Category C_Foo_2: Public C_Foo & lt; Bar_2 & gt; {...}; Category C_Foo_3: Public C_Foo & lt; Bar_3 & gt; {...};  

and immediately follows:

  C_Foo_1 foo1; C_Foo_2 foo2; C_Foo_3 foo3;  

I have a set of normal operations, all of which are defined on C_Foo, that I want to display on foo1, foo2, and foo3. I have tried the following:

  vector & lt; C_Foo * & gt; V; V.push_back (& ​​amp; foo1); V.push_back (& ​​amp; foo2); V.push_back (& ​​amp; foo3);  

But I get the compilation errors, probably because the compiler is not sure how to go from C_Foo_1 to C_Foo.

Is it possible to do something like this? I want to be able to loop through foo1 .. fooN and to perform the same actions on all of them, without copying and pasting without the boilerplate code:

  foo1.do_stuff (); Foo2.do_stuff (); Foo3.do_stuff ();  

Thank you for your help.

You can do this if the function is not dependent on the template parameter:

< Pre> // Note: Not a template class C_Foo_Common {Public: Virtual Zero do_stuff () = 0; }; Template & lt; Typename T & gt; Class C_Foo: Public C_Foo_Common {Virtual Zero do_stuff () {// do stuff ...}}; Vector & lt; C_Foo_Common * & gt; V; V.push_back (& ​​amp; foo1); V.push_back (& ​​amp; foo2); V.push_back (& ​​amp; foo3); // Now, you can iterate and call do_stuff on them.

But if C_Foo_Common requires the function type T (for example, another return type depending on the t), then it is now possible Not C_Foo & lt; Bar_1 & gt; C_Foo & lt; Bar_2 & gt; There is a different type than . You can use unions with discrimination instead. They keep track of what they are stored and are completely normal:

  typedef boost :: variant & lt; C_fu & lt; Bar_1 & gt; *, C_fu & lt; Bar_2 & gt; *, C_fu & lt; Bar_3 & gt; * & Gt; Variant_type; Of vector & lt; Variant_type & gt; V; V.push_back (& ​​amp; foo1); V.push_back (& ​​amp; foo2); V.push_back (& ​​amp; foo3);  

The difference knows what he stores, and can call overloaded tasks on the types of storage that can be stored on it. Read the documentation for more information on what to include in the variant.


Comments