mercredi 28 novembre 2018

std::bind and variadic template function

Is this even possible?

#include <iostream>
#include <functional>

enum class Enum {a, b, c };

class Dispatch {
    public:
    void check(uint16_t) { std::cout << "check 16\n"; }
    void check(uint32_t) { std::cout << "check 32\n"; }
    void check(uint64_t) { std::cout << "check 64\n"; }

    template<Enum E, typename... A>
    void event(A&&... args) {
        tag_event(Tag<E>(), std::forward<A>(args)...);
    }

    private:
    template<Enum E> struct Tag {};    
    void tag_event(Tag<Enum::a>, uint16_t) { std::cout << "a\n"; }
    void tag_event(Tag<Enum::b>, uint16_t) { std::cout << "b\n"; }
    void tag_event(Tag<Enum::c>, uint16_t) { std::cout << "c\n"; }
};

void exec(std::function<void()>&& func) { func(); }

int main() {
    Dispatch d;

    // all good    
    exec(std::bind(static_cast<void(Dispatch::*)(uint16_t)>(&Dispatch::check), &d, uint16_t()));
    exec(std::bind(static_cast<void(Dispatch::*)(uint32_t)>(&Dispatch::check), &d, uint32_t()));
    exec(std::bind(static_cast<void(Dispatch::*)(uint64_t)>(&Dispatch::check), &d, uint64_t()));

    // all good
    d.event<Enum::a>(uint16_t());
    d.event<Enum::b>(uint16_t());
    d.event<Enum::c>(uint16_t());

    // but how do we bind an event<> call?
    exec(std::bind(static_cast<void(Dispatch::*)(uint16_t)>(&Dispatch::event<Enum::a>), &d, uint16_t()));
}

So I'm trying to bind a call to the variadic template method but get the following compiler error...

In function 'int main()':
42:86: error: no matches converting function 'event' to type 'void (class Dispatch::*)(uint16_t) {aka void (class Dispatch::*)(short unsigned int)}'
13:10: note: candidate is: template<Enum E, class ... A> void Dispatch::event(A&& ...)

Any suggestions short of exposing all the tag overloads instead?

Aucun commentaire:

Enregistrer un commentaire