簡體   English   中英

通過std :: function引用的Functor

[英]Functor reference through a std::function

基本上,我想有以下語義:

#include <functional>
#include <iostream>

class test
{
  public:
    void add(std::function<void()> f)
    {
      f();
    }

    void operator()()
    {
      ++x;
    }

    int x = 33;
};

int main()
{
  test t;
  t.add(t);
  // wanted: x == 34 instead: x == 33 since add(t) copies it
}

我理解std :: function包裝了一個可調用對象的副本,但有沒有辦法使用std :: function獲取對可調用對象的引用?

您想使用std::ref模板函數為您的實例創建一個引用包裝器

std::reference_wrapper是一個類模板,它在可復制的可分配對象中包裝引用。

函數模板refcref是輔助函數,它們生成std::reference_wrapper類型的對象,使用模板參數推導來確定結果的模板參數。

你會像這樣使用它:

t.add(std::ref(t));

暫無
暫無

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

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