[英]mem_fn to function of member object
我正在修改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()
將成員函數指針作為參數,即
auto y = std::mem_fn(&Int::GetInt);
auto b = y(wrapper.test);
據我所知, std::mem_fn()
或多或少是過時的,因為lambda表達式 。 例如
auto y = [](IntWrapper const&wrapper) { return wrapper.test.GetInt(); };
auto b = y(wrapper); // note: no need to get hold of member 'test'
你的語法錯了, &IntWrapper::test
是指向成員的指針。
我從未見過&IntWrapper::test.GetInt
,我甚至不知道它是如何被解析的。
也許這就是你想要的
auto y = std::mem_fn(&decltype(IntWrapper::test)::GetInt);
auto b = y(wrapper.test);
因為無論如何都沒有指定std::mem_fn
的返回類型,我只是看不出使用它而不是一些lambda函數的原因:
auto x = [&wrapper]{ return wrapper.GetWrappedInt(); };
int a = x();
要么:
auto x = [](const IntWrapper& wrapper){ return wrapper.GetWrappedInt(); };
int a = x(wrapper);
我甚至認為這些更好,因為編譯器可以有更好的優化機會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.