簡體   English   中英

std :: bind和可變參數模板函數

[英]std::bind and variadic template function

這有可能嗎?

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

除了公開所有標簽重載以外,還有什么建議嗎?

我建議按照注釋中的建議通過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()方法,該方法還應說明接收到的類型; 我建議與您的event()方法的通用引用簽名兼容的uint16_t const & (而不是uint16_t )(我想其他組合也是可行的,但是對於uint16_t激活move語義...我認為這是多余的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM