c++variadic-templatesconversion-operator

Creating functions for each variadic template type


I have several functions for a class which do the exact same thing but with a different type.

class ExampleWrapper
{
public:
    operator T1() { ... }
    operator T2() { ... }
    operator T3() { ... }
};

Is it possible to combine these into a single template parameter:

class ExampleWrapper : public Wrapper<T1, T2, T3>
{
   // does the same as above
};

Bonus: Do you think this that having these functions explicitly there (perhaps with a proper name) is more readable?

Edit:
T1, T2, T3 are some types specified by some API.


Solution

  • Since we don't have reflection or template for yet, you can use variadic inheritance to compose a type with all the member function we need.

    Let's start with the one type case:

    template<typename T>
    struct Wrapper {
        operator T() { ... }
    };
    

    We can now inherit multiple times from this struct using pack expansion:

    template<typename... Ts>
    struct WrapperVariadic : Wrapper<Ts>... {};
    

    Then, inherit from that:

    struct HaveManyWrappers : WrapperVariadic<T1, T2, T3> {
        // ...
    };