假设以下代码:
class MyTest
{
public:
void CallFoo()
{
}
MyTest()
{
std::function<void()> func = &decltype(*this)::CallFoo;
}
};
int main()
{
MyTest t;
}
我所拥有的内容不会编译,但实质上我需要能够使用decltype
来获取*this
类型的成员函数的地址。通常你只需&MyTest::CallFoo
。
这可能吗?如果是这样,那么正确的语法是什么?
答案 0 :(得分:7)
你可以做到
&std::remove_pointer_t<decltype(this)>::CallFoo
或在C ++ 11中(抱歉,只是注意到标签)
&std::remove_pointer<decltype(this)>::type::CallFoo
问题在于decltype(*this)
提供MyTest&
而不是MyTest
,因为*this
是左值。
但是,std::function<void()>
不起作用,因为需要使用MyTest
调用MyTest*
的非静态成员函数作为this
。如果希望调用者指定对象,可以使用std::function<void(MyTest*)>
或std::function<void(decltype(this))>
。如果你想绑定this
,你应该只使用一个lambda,它会更容易:
auto func = [this]{ CallFoo(); };
答案 1 :(得分:0)
警告:包含一个宏。负责任地使用。
使用以下宏来使decltype
“明智地”使用引用。
template<class T> struct TypeOf { typedef typename std::remove_reference<T>::type type; };
#define TYPE(x) TypeOf<decltype(x)>::type