C++ 获取成员函数的地址而不引用实例';是用具体的名字来命名的吗?
现在我们有了C++ 获取成员函数的地址而不引用实例';是用具体的名字来命名的吗?,c++,c++11,visual-studio-2012,auto,C++,C++11,Visual Studio 2012,Auto,现在我们有了auto关键字,我希望能够获取类实例成员的地址,而不必静态引用其类 e、 g.(老斯科尔) c++11使用auto auto & foo = m_holder.GetInteresting(); foo.SetEnableNotification(false); ScopeGuard restore_notifications = MakeObjGuard(foo, &foo.SetEnableNotification, true); // do stuf... 但
auto
关键字,我希望能够获取类实例成员的地址,而不必静态引用其类
e、 g.(老斯科尔)
c++11使用auto
auto & foo = m_holder.GetInteresting();
foo.SetEnableNotification(false);
ScopeGuard restore_notifications = MakeObjGuard(foo, &foo.SetEnableNotification, true);
// do stuf...
但是,&foo.memfun不会编译。这方面的语法/规范方法是什么?如果可以避免的话,我们当然不想提及具体类型的foo,因为否则auto
似乎是一种弱调味品。事实上,不?这应该有效(至少在GCC 4.7.2中):
ScopeGuard还原\u通知=MakeObjGuard(foo,
&std::remove_reference::type::SetEnableNotification,true);
我在简化的情况下尝试了它,它编译得很好。您是否尝试过
&decltype(foo)::SetEnableNotification
?我想现在的方法(至少对于类似范围保护的类来说)应该是使用lambda:auto restore\u notifications=make\u scope\u guard([&]{foo.SetEnableNotification(true);})代码>不幸的是,它没有&decltype(foo)::SetEnableNotifications
->错误C2039:“SetEnableNotifications”:不是“
全局命名空间”的成员。@Mordachai这是Visual Studio中的一个错误,在decltype(…)
之后使用:
总是失败。我看到的一个解决方法是键入defdecltype(…)
,然后使用typedef引用嵌套的内容。@Xeo Yep,我看到了您对下面答案的评论。但是VS报告的错误是不正确的。不正确,因为foo
是MyInterestingClass&
。感谢您演示如何使它工作。我认为@GManNickG使用lambda是正确的。上面的语法还有很多需要改进的地方。当然,我会把它留在这里,因为它回答了问题,以防其他人需要它。
auto & foo = m_holder.GetInteresting();
foo.SetEnableNotification(false);
ScopeGuard restore_notifications = MakeObjGuard(foo, &foo.SetEnableNotification, true);
// do stuf...
ScopeGuard restore_notifications = MakeObjGuard(foo,
&std::remove_reference<decltype(foo)>::type::SetEnableNotification, true);