int a = 0;
int c = 0;
int& b = c;
std::vector<int> arrInt{ 1,2,3,4,5,6,7,8,9 };
std::for_each(arrInt.begin(), arrInt.end(), std::bind(&DlgRWCoordinateTable::FindMax, this, std::placeholders::_1, std::ref(a)));
std::for_each(arrInt.begin(), arrInt.end(), std::bind(&DlgRWCoordinateTable::FindMax, this, std::placeholders::_1, std::ref(b)));
std::ref 返回了一个维护对应类型的指针的类(reference_wrapper)对象
由于实现了对应类型的隐式转换的接口 operator _Ty&() const _NOEXCEPT,参数在被需要时,可隐式转换为对应类型。
总结:
如果接口没有对应的指针传出接口,只有引用参数传出接口,可使用std::ref来使用是std::bind。
下方是标注库reference_wrapper实现代码:
template<class _Ty>
class reference_wrapper
: public _Weak_types<_Ty>::type
{ // stand-in for an assignable reference
public:
static_assert(is_object<_Ty>::value || is_function<_Ty>::value,
"reference_wrapper<T> requires T to be an object type "
"or a function type.");
typedef _Ty type;
reference_wrapper(_Ty& _Val) _NOEXCEPT
: _Ptr(_STD addressof(_Val))
{ // construct
}
operator _Ty&() const _NOEXCEPT
{ // return reference
return (*_Ptr);
}
_Ty& get() const _NOEXCEPT
{ // return reference
return (*_Ptr);
}
template<class... _Types>
auto operator()(_Types&&... _Args) const
-> decltype(_STD invoke(get(), _STD forward<_Types>(_Args)...))
{ // invoke object/function
return (_STD invoke(get(), _STD forward<_Types>(_Args)...));
}
reference_wrapper(_Ty&&) = delete;
private:
_Ty *_Ptr;
};