Is it possible to define a method overload for each element of a template parameter pack?

87 Views Asked by At

Suppose I have a class template with a type template parameter pack, like

template<typename... types>
class Foo {};

Is there any way I could define methods in Foo, say void bar(T x); with overloads for each type T in the parameter pack types?

2

There are 2 best solutions below

0
康桓瑋 On BEST ANSWER

You can have Foo inherit each base with void bar(T x):

template<typename T>
struct FooBase {
  void bar(T x);
};

template<typename... types>
struct Foo : FooBase<types>... {
  using FooBase<types>::bar...;
};
1
bolov On

You can just have a template bar:

template<typename... types>
struct Foo
{
    template <class T>
    void bar(T x)
    {
    }
};

If you want to restrict to just one of types then you can use std::same_as concept:

template<typename... types>
struct Foo
{
    template <class T>
        requires (... || std::same_as<T, types>)
    void bar(T x)
    {
    }
};

But this will not accept arguments convertible to one of types (but not one of them). So you can use std::convertible_to instead:

template<typename... types>
struct Foo
{
    template <class T>
        requires (... || std::convertible_to<T, types>)
    void bar(T x)
    {
    }
};

This still differs a bit from having actual non-templated overloads because it will not generate "ambiguous overload error" if that's something you care about.