我正在摆弄std::mem_fn
并且无法设法将其绑定到结构成员的数据/函数(更深一层)。
我希望代码能比我描述的更好地显示问题,因为我不熟悉这些术语。
#include <functional>
struct Int
{
Int(int _x = 0) : x(_x) {}
int GetInt() const { return x; }
int x;
};
struct IntWrapper
{
IntWrapper(int _x = 0) : test(_x) {}
int GetWrappedInt() const { return test.GetInt(); }
Int test;
};
int main()
{
IntWrapper wrapper{ 123 };
auto x = std::mem_fn(&IntWrapper::GetWrappedInt);
//auto y = std::mem_fn(&IntWrapper::test.GetInt); // ERROR
//auto z = std::mem_fn(&IntWrapper::test.x); // ERROR
int a = x(wrapper);
//int b = y(wrapper);
//int c = z(wrapper);
//std::cin.ignore();
return 0;
}
错误信息如下:
error C2228: left of '.GetInt' must have class/struct/union
error C2672: 'std::mem_fn': no matching overloaded function found
error C3536: 'y': cannot be used before it is initialized
error C2064: term does not evaluate to a function taking 1 arguments
问题:
是否可以进行这些绑定?我需要std::bind
为了这?
根据规范,std::mem_fn() http://en.cppreference.com/w/cpp/utility/functional/mem_fn将成员函数指针作为参数,即
auto y = std::mem_fn(&Int::GetInt);
auto b = y(wrapper.test);
据我所知,std::mem_fn()
或多或少已经过时了,因为lambda 表达式 http://en.cppreference.com/w/cpp/language/lambda。例如
auto y = [](IntWrapper const&wrapper) { return wrapper.test.GetInt(); };
auto b = y(wrapper); // note: no need to get hold of member 'test'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)