Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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> {
    // ...
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading