std :: bind和可变参数模板函数

时间:2018-11-28 15:49:11

标签: c++ c++11 templates variadic-templates stdbind

这有可能吗?

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

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

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

除了公开所有标签过载之外,还有没有建议?

1 个答案:

答案 0 :(得分:0)

我建议按照注释中的建议通过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来说,可以激活移动语义。 ..我想这是多余的。