James
James

Reputation: 2999

c++: Using class type as parameter

I have multiple format types which each have a name and a value assigned to them. I want to be able to pass in the format type as a parameter into a method. The declaration will look like CreateFile(4,3,2,UGS12_FMT), where UGS12_FMT is a c++ type.

Notice that I am not passing in an instance as a parameter. Any suggestions on how to accomplish this?

Upvotes: 2

Views: 1101

Answers (3)

Walter
Walter

Reputation: 45484

You cannot pass in a typename as a normal function argument, i.e. your snippet

using UGS12_FMT = some_type;
auto file = CreateFile(4,3,2,UGS12_FMT);  // error

will never work (except when you make CreateFile a macro, which is strongly discouraged).

Instead, you can essentially use one of three alternative techniques.

  1. Overload the function to take different arguments of empty type (so-called tag-dispatching):

    // declarations of tag types
    struct format1 {} fmt1; 
    struct format2 {} fmt2; // etc
    // overloaded file creation functions
    file_type CreateFile(args, format1);
    file_type CreateFile(args, format2);
    // usage:
    auto file = CreateFile(4,3,2,fmt1);  // use format1
    
  2. Use a template (and specialise it for different format types)

    template<typename Format>
    file_type CreateFile(args);   // generic template, not implemented
    template<> file_type CreateFile<Format1>(args); // one speciliasation
    template<> file_type CreateFile<Format2>(args); // another speciliasation
    
    auto file = CreateFile<Format1>(4,3,2);   // usage
    
  3. Pass the information using an enum type.

    enum struct format {
      f1,                // indicates Format1
      f2 };              // indicates Format2
    file_type CreateFile(args,format);
    
    auto file = CreateFile(4,3,2,format::f1);
    

Finally, you can combine these various approaches using traits classes as similar techniques.

Upvotes: 2

J.N.
J.N.

Reputation: 8431

You want to look at what is RTTI. Support varies depending on compiler, but basic functionality is there. A good place to start here.

Note that for instance for GCC you'll need helper functions to unmangle the names given by type_info objects.

EDIT: of course, make sure templates can't offer what you want first, it would be the preferred way.

Upvotes: 0

Davidsun
Davidsun

Reputation: 721

There could be many methods to do this. The first method, which is the most recommended, is to inherit each of the class from a common parent class, since they share "name" and "value", as described previously.

If you really need to know what class it is in function "CreateFile", you'd better change the implement of the function, using multiple functions, like

CreateFile(ClassA a)
CreateFile(ClassB a)

instead of

CreateFile(Class x)
    if x is an instance of ClassA
        doSomething ...
    else if x is an instance of ClassB
        doSomething ...

Upvotes: 0

Related Questions