3

How do I get this code to compile?

struct type1 {};
struct type2 {};

struct handler1
{
    void handle(type1){}
};

struct handler2
{
    void handle(type2){}
};

template <typename... Handlers>
struct TheHandler : Handlers...
{
    using Handlers::handle...; // DOESN'T COMPILE
};

TheHandler<handler1, handler2> handler;
handler.handle(type1());
Nikola Smiljanić
  • 26,745
  • 6
  • 48
  • 60
  • 1
    [This works in C++17](https://godbolt.org/g/qoHVWq). It was added in C++17 (the `using` expanding parameter packs). It works there in C++14 as a compiler extension – Justin Oct 17 '17 at 00:40
  • @Justin Thanks but I'm stuck with C++14 for the time being. – Nikola Smiljanić Oct 17 '17 at 00:45
  • As with all parameter pack expansions, you can rewrite this with recursion, if I'm not mistaken – Passer By Oct 17 '17 at 00:47
  • 1
    Yes, you can rewrite this with recursion as per the paper that proposed parameter-pack expansion with `using`: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0195r1.html – Justin Oct 17 '17 at 00:49

1 Answers1

4

using with parameter packs was added in C++17, so your code would just work in C++17.

As a workaround for C++14, you can use recursion. The proposal for using... shows how to do this:

template <typename Handler0, typename... Handlers>
struct TheHandler : Handler0, TheHandler<Handlers...>
{
    using Handler0::handle;
    using TheHandler<Handlers...>::handle;
};

template <typename Handler>
struct TheHandler<Handler> : Handler
{
    using Handler::handle;
};

On Godbolt

It is possible to achieve logarithmic recursion depth, if you wish to do so.

Justin
  • 24,288
  • 12
  • 92
  • 142