type as function argument

Dec 14, 2011 at 12:24pm
How can I pass a variable type as function argument, e.g. function(a) works with variables of type a and so on?

The specific problem: I have a class with quite a big function which creates class objects. Classes derived from this class should create classes of another type than the base class (though not in every case of the same type as the calling object). The initial function doesn't have any arguments (i.e. void), and the argument should be the type to create.

I did quite some googling but didn't find the answer...
Dec 14, 2011 at 1:01pm
Do you mean templates ?
Dec 14, 2011 at 1:08pm
I don't know templates, so: Maybe I do.

I put together a little example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Class0 {
   ...
};

class Class1 : public Class0 {
   ...
   virtual void function1 ( [type1] ) {
      ...
      Class0 *obj = new [type1];
      ...
   }
   ...
};

class Class2 : public Class1 {
   ...
   void function1 ( [type2] ) {
      Class1::function1 (x);
      ...
      Class0 *obj = new [type2];
      ...
   }
   ...
};

The types given as function arguments are all derived from Class0, that's why I all assign them to a Class0-pointer in the code above (it's not a typo)...
Last edited on Dec 14, 2011 at 1:11pm
Dec 14, 2011 at 3:57pm
Yes, templates is what I meant! Thanks for the input. Some more googling and trying out led me to the solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Class0 {
   ...
};

class Class1 : public Class0 {
   ...
   template <typename Type> void function1 (void) {
      ...
      Class0 *obj = new Type;
      ...
   }
   ...
};

class Class2 : public Class1 {
   ...
   void function1 (void) {
      Class1::function1<type_x> ();
      ...
   }
   ...
};

At least that's part of the whole solution because with template, I can't make a function virtual anymore, so I have to change my concept a bit. But that's doable.
Topic archived. No new replies allowed.