簡體   English   中英

std::bind 不適用於 1 個參數

[英]std::bind not working with 1 parameter

添加占位符時, std::bind遇到了一些問題我的代碼有點大,所以我只會堅持要點

#define GETFUNC(a) (std::bind(&app::a, this, std::placeholders::_1))
class button{
button(<other parameters here>, std::function<void(int)>) { ... }
..
std::function<void(int)> onhover;
..
};

class app{
app(){
elements.push_back(buttonPtr( new button(<other parameters>, GETFUNC(onHover) );
..
typedef std::unique_ptr<button> buttonPtr;
std::vector<buttonPtr> elements;
..
void onHover(int i) {}
}

這段代碼在std::bind失敗(我從錯誤日志中得到了那么多)但如果我改變了:

  • 所有std::function<void(int)>std::function<void()>
  • onHover(int i)onHover()
  • std::bind(&app::a, this, std::placeholders::_1)std::bind(&app::a, this)

關於為什么會發生這種情況以及我該如何解決的任何想法?

它工作正常。 檢查這一點並尋找與您的代碼的差異。

#include <functional>
#include <iostream>


struct app
{
  std::function<void (int)>
  get_func ()
  {
    return std::bind (&app::on_hover, this, std::placeholders::_1);
  }

  void on_hover (int v)
  {
    std::cout << "it works: " << v << std::endl;
  }
};

int
main ()
{
  app a;

  auto f = a.get_func ();
  f (5);
}

暫無
暫無

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

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