Using an enumeration as a template parameter

后端 未结 4 706
情书的邮戳
情书的邮戳 2020-12-13 09:29

I would like to use a template class to provide some common functionality to some child classes that are very similar. The only variation is the enumeration that each uses.

相关标签:
4条回答
  • 2020-12-13 09:59

    Enumerations can be template parameters in exactly the same way that ints can.

    enum Enum { ALPHA, BETA };
    
    template <Enum E> class Foo {
        // ...
    };
    
    template <> void Foo <ALPHA> :: foo () {
        // specialise
    }
    
    class Bar : public Foo <BETA> {
        // OK
    }
    

    But you simply haven't provided a definition for E_EnumerationBase::E_EnumerationBase()

    This isn't a problem with templates or inheritence. It's the same as if you written this:

    struct Foo {
        Foo ();
    }
    int main () {
        Foo foo;
    }
    
    0 讨论(0)
  • 2020-12-13 09:59

    Just for reference, as you seem to use Qt: Just have a look at Q_ENUM, QMetaEnum and QMetaEnum::fromType. These may come handy to initialize your dictionary.

    0 讨论(0)
  • 2020-12-13 10:05

    You cannot move definition of template function to separate source file.

    There it wouldn't be compiled at all, because templates can't be compiled, only template instances can.

    Your code in separate file isn't get compiled, that's why you actually have no definition for E_EnumerationBase<TableEventEnum>::E_EnumerationBase(). That's why you get linker error.

    Just move all template code to your header.

    0 讨论(0)
  • 2020-12-13 10:06

    The syntax goes for value arguments like it is for typename arguments. Basically, you just replace typename with the name of your enum:

    enum Foo { Bar, Frob };
    
    template <Foo F> struct Boom {};  // primary template
    template <> struct Boom<Bar> {};  // specialization of whole class
    
    ...
    
    template <> void Boom<Frob>::somefun() {}  // specialization of single member
    
    0 讨论(0)
提交回复
热议问题