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?
I suggest to pass through a lambda function, as suggested in comments.
Anyway, if you want to pass to std::bind()
, seems to me that a possible solution is
// ..................................................VVVVVVVV <-- ad this
exec(std::bind(static_cast<void(Dispatch::*)(uint16_t const &)>
(&Dispatch::event<Enum::a, uint16_t const &>), &d, uint16_t()));
// ...........................^^^^^^^^^^^^^^^^^^ <-- and this
I mean: you have to select the event()
method explicating also the received type; I suggest uint16_t const &
(instead of uint16_t
) that is compatible with universal reference signature of your event()
method (I suppose other combinations are possible but for a uint16_t
activate move semantics... I suppose it's superfluous).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.