AdyAdy AdyAdy -4 years ago 50
C++ Question

C++ Multiple definitons of member function, based on enum template argument

Consider this code:

template<typename T, SomeEnum mode> struct TC{

T data;

//...

void doStuff();
};


can "doStuff" have more than one definitions based on the the enum value set for the template?

TC<int, SomeEnum::MODE_1> tc1; tc.doStuff(); //do some stuff
TC<int, SomeEnum::MODE_2> tc2; tc.doStuff(); //do some other stuff


(I don't mean save "mode" and make a branch on it but actually multiple definitions.)

Answer Source

You can do tag dispatch. Just provide an overload for each packaged value of the enum:

template<typename T, SomeEnum mode> struct TC{

    T data;

    //...
    template<SomeEnum v>
    using tag_type = std::integral_constant<SomeEnum, v>;

    void reallyDoStuff(tag_type<SomeEnum::MODE_1>);
    void reallyDoStuff(tag_type<SomeEnum::MODE_2>);

    void doStuff() { reallyDoStuff(tag_type<mode>{}); }
};

Because the member functions of a class template won't be instantiated unless used, you'd only instantiate one definition of reallDoStuff (the proper one) for every instance of TC.

When in doubt, prefer function template overloading to specialization. It's usually the superior alternative.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download