C++ generic way to define multiple functions with a template

  • A+
Category:Languages

In C++ is it possible to define multiple methods based of the number of template parameters provided? Similar to how variadic functions work?

With functions I can do

template <class ...Args> struct VariadicFunctionCallback {     typedef std::function<void(std::shared_ptr<Args>...)> variadic; }; 

But what I want to know is if I could do something similar but to create multiple functions instead of multiple arguments

template <class ...FunctionArg> class Example {      void Function(FunctionArg)... } 

Which would then allow me to do something like

template <> class Example<int, float> {     void Function(int i) {         ...     }      void Function(float f) {         ...     } } 

And if this is possible what are the advantages over my current setup which is like

template<class EventType> class EventHandler { public:     void HandleEvent(const std::shared_ptr<EventType>& event) {     } };  class ExampleEvent : public Event<ExampleEvent> {  };  class ExampleHandler : public EventHandler<ExampleHandler>, EventHandler<Events::ShutdownEvent> { public:     void HandleEvent(const std::shared_ptr<ExampleEvent> &event);      void HandleEvent(const std::shared_ptr<Events::ShutdownEvent> &event); }; 


I suppose you can make Example a sort of recursive self-inheritancing class; something as

    template <typename ...>     struct Example      {        // dummy Function() to end the recursion        void Function ()         { }      };      template <typename T0, typename ... Ts>     struct Example<T0, Ts...> : public Example<Ts...>      {        using Example<Ts...>::Function;         void Function (T0 const &)         { };      }; 

So you can write

int main ()  {    Example<int, long, float>  e0;     e0.Function(0);    e0.Function(0L);    e0.Function(0.0f);  } 

-- EDIT --

The OP ask

Could a specialisation then be preformed on top of this?

Do you mean something as follows?

template <typename ...> struct Example  {    // dummy Function() to end the recursion    void Function ()     { }  };  template <typename T0, typename ... Ts> struct Example<T0, Ts...> : public Example<Ts...>  {    using Example<Ts...>::Function;     void Function (T0 const &)     { };  };  template <typename ... Ts> struct Example<float, Ts...> : public Example<Ts...>  {    void FunctionFloat (float const &)     { };  };  int main ()  {    Example<int, long, float>  e0;     e0.Function(0);    e0.Function(0L);    e0.FunctionFloat(0.0f);    //e0.Function(0.0f); // compilation error  } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: