2016-09-08 13 views
0

請考慮下面的模板函數,這需要一個可調用,計算它,並返回結果(只用於說明目的):爲什麼可以使用std :: ref將成員函數用作可調用類型?

template<typename F, typename... A> 
auto evaluate(F&& f, A&&... args) -> decltype(f(std::forward<A>(args)...)) 
{ 
    return f(args...); 
} 

這適用於獨立的功能,但通過成員函數時,它打破例如如下所示,其中fooFoo一個實例:

evaluate(&Foo::bar, foo, ...); 

它抱怨不能夠調用成員函數:

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘f (...)’, 
e.g. ‘(... ->* f) (...)’ auto evaluate(F&& f, A&&... args) -> decltype(f(std::forward<A>(args)...)) 

結束語在std::reff確實允許合格的成員函數:

template<typename F, typename... A> 
auto evaluate(F&& f, A&&... args) -> decltype(std::ref(f)(std::forward<A>(args)...)) 
... 

爲什麼這項工作?

+1

因爲標準庫是真棒 –

+0

鏈接文件的位置:http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator() –

+0

@RichardHodges在這裏傳遞給成員函數的'this'指針是什麼? – songyuanyao

回答

2

如果包裝對象可調用,使reference_wrapper可調用的功能是將對函數對象的引用傳遞到標準算法等的基礎。

這裏我們創建引用的元組函數對象:

int main() 
{ 
    struct A { 
     void operator()() const { 
      std::cout << "A\n"; 
     } 
    }; 

    struct B { 
     void operator()() const { 
      std::cout << "B\n"; 
     } 
    }; 

    A a; 
    B b; 

    auto ab = std::tie(a, b); 

    std::get<0>(ab)(); 
    std::get<1>(ab)(); 
} 

在這裏,我們傳遞給狀態函數對象的引用到一個標準的算法:

struct EqualAndCount 
{ 
    EqualAndCount(char sought) : sought_(sought) {} 

    template<class R> 
    bool operator()(R const& r) 
    { 
     counter_++; 
     return sought_ == r; 
    } 
    std::size_t counter_ = 0; 
    char sought_; 
}; 

int main() 
{ 
    EqualAndCount eq('j'); 
    auto s = std::string("abcdefghijklmnop"); 
    auto i = std::find_if(s.begin(), s.end(), std::ref(eq)); 

    std::cout << "searched " << eq.counter_ << " chars"; 
    if (i == s.end()) 
     std::cout << " and did not find it\n"; 
    else 
     std::cout << " and found it\n"; 
} 

預期輸出:

searched 10 chars and found it 

爲什麼這個w掃?

由於std::reference_wrapper::operator()被寫入神話INVOKE的術語(至多C++ 14)和在std::invoke術語(C++ 17)。

文檔瀏覽:

http://en.cppreference.com/w/cpp/utility/functional/invoke

相關問題