0
請考慮下面的模板函數,這需要一個可調用,計算它,並返回結果(只用於說明目的):爲什麼可以使用std :: ref將成員函數用作可調用類型?
template<typename F, typename... A>
auto evaluate(F&& f, A&&... args) -> decltype(f(std::forward<A>(args)...))
{
return f(args...);
}
這適用於獨立的功能,但通過成員函數時,它打破例如如下所示,其中foo
是Foo
一個實例:
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::ref
f
確實允許合格的成員函數:
template<typename F, typename... A>
auto evaluate(F&& f, A&&... args) -> decltype(std::ref(f)(std::forward<A>(args)...))
...
爲什麼這項工作?
因爲標準庫是真棒 –
鏈接文件的位置:http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator() –
@RichardHodges在這裏傳遞給成員函數的'this'指針是什麼? – songyuanyao