[英]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? 除了公开所有标签重载以外,还有什么建议吗?
I suggest to pass through a lambda function, as suggested in comments. 我建议按照注释中的建议通过lambda函数。
Anyway, if you want to pass to std::bind()
, seems to me that a possible solution is 无论如何,如果您想传递给
std::bind()
,对我来说,可能的解决方案是
// ..................................................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; 我的意思是:您必须选择
event()
方法,该方法还应说明接收到的类型; 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). 我建议与您的
event()
方法的通用引用签名兼容的uint16_t const &
(而不是uint16_t
)(我想其他组合也是可行的,但是对于uint16_t
激活move语义...我认为这是多余的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.