gpt4 book ai didi

c++ - std::bind 和可变参数模板函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:42:29 29 4
gpt4 key购买 nike

这可能吗?

#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()));
}

所以我尝试将调用绑定(bind)到可变参数模板方法,但出现以下编译器错误...

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&& ...)

除了公开所有标签重载之外还有什么建议吗?

最佳答案

我建议按照评论中的建议传递一个 lambda 函数。

无论如何,如果你想传递给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

我的意思是:你必须选择 event() 方法来说明接收到的类型;我建议 uint16_t const &(而不是 uint16_t)与您的 event() 方法的通用引用签名兼容(我想其他组合是可能,但对于 uint16_t 激活移动语义...我想这是多余的)。

关于c++ - std::bind 和可变参数模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53523281/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com