簡體   English   中英

正確使用std :: function :: target

[英]using std::function::target correctly

任何人都可以幫我實現下面的函數test ,以便它接受任何Callablestd::function ,如果std::function的目標是Callable,則返回true 我一直在嘗試各種各樣的事情,但它們都沒有一直在工作,我甚至無法弄清楚為什么他們為他們工作的案件工作。

#include <type_traits>
#include <iostream>
#include <functional>

int foo(int) {return 0;}
int faz(int) {return 0;}

struct {
    int operator()(int) {return 0;}
} bar, baz;

template<class F1, class F2>
bool
test(F1&& f1, std::function<F2> f2) {
    //return f2.template target<F1>() == f1;
    //return f2.template target<F2>() == &f1;
    //return *f2.template target<std::add_pointer_t<F1>>() == &f1;
    //return *f2.template target<std::add_pointer_t<F2>>() == &f1;
    //return *f2.template target<std::add_pointer_t<F1>>() == f1;
    //...
}

int main() {
    std::function<int(int)> f{foo};
    std::cout << test(foo, f) << std::endl;
    std::cout << test(faz, f) << std::endl;
    f = bar;
    std::cout << test(bar, f) << std::endl;
    std::cout << test(baz, f) << std::endl;
}

http://coliru.stacked-crooked.com/a/11346a171199af81

template<class F1, class F2>
bool test(F1&& f1, std::function<F2> f2) {
  auto* ptr =  f2.template target<std::decay_t<F1>>();
  if (!ptr) return false;
  return *ptr == f1;
}

這對lambdas不起作用,因為lambdas沒有operator==

這對你的struct不起作用,因為它沒有operator==

它適用於函數指針,因為它們有一個operator==

struct bob {
  int operator()(int) {return 0;}
  bool operator==(bob const& o)const{return true;}
} bar, baz;

現在它有效。 當然, barbaz比較任何bob

現在,函數存儲您傳遞的任何內容的副本 因此,您無法將函數中存儲的函數的地址與其復制的函數的地址進行比較,並獲得有用的結果。

std::ref將指針包裝起來以作為參考。

暫無
暫無

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

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