我一直在查看 gcc-4.7.2 中 std::function
和 std::bind
的源代码,发现了一些用于成员的语法我不明白的函数指针。
我不明白的是_Maybe_wrap_member_pointer
的特殊化:
template<typename _Tp, typename _Class>
struct _Maybe_wrap_member_pointer<_Tp _Class::*> // note no comma here
为什么
_Tp
和_Class::*
之间没有逗号?给定成员函数
void foo::bar()
(在我下面的示例应用程序中),_Tp
和_Class::*
解析到这里?
下面是我的示例应用程序,它绑定(bind)了一个成员函数指针和对象。 (我已经提取了与 std::bind
specialisations/internals for member functions 相关的源代码)
#include <iostream>
#include <functional>
template<typename T>
struct _Maybe_wrap_member_pointer;
template<typename _Tp, typename _Class>
struct _Maybe_wrap_member_pointer<_Tp _Class::*> // <-- I don't understand this
{ // why not <_Tp, _Class::*>
typedef std::_Mem_fn<_Tp _Class::*> type;
static type __do_wrap(_Tp _Class::* __pm)
{
return type(__pm);
}
};
template<typename _Func, typename... _BoundArgs>
struct _Bind_helper
{
typedef _Maybe_wrap_member_pointer<typename std::decay<_Func>::type> __maybe_type;
typedef typename __maybe_type::type __func_type;
typedef std::_Bind<__func_type(typename std::decay<_BoundArgs>::type...)> type;
};
template<typename _Func, typename... _BoundArgs>
inline
typename _Bind_helper<_Func, _BoundArgs...>::type
bind(_Func&& __f, _BoundArgs&&... __args)
{
typedef _Bind_helper<_Func, _BoundArgs...> __helper_type;
typedef typename __helper_type::__maybe_type __maybe_type;
typedef typename __helper_type::type __result_type;
return __result_type(__maybe_type::__do_wrap(std::forward<_Func>(__f)),
std::forward<_BoundArgs>(__args)...);
}
struct foo
{
void bar()
{
std::cout << __func__ << std::endl;
}
};
int main()
{
foo f;
std::function<void()> fun = bind(&foo::bar, f);
fun();
exit(0);
}
最佳答案
这确实是用于将成员指针类型指定为模板参数的语法。
假设你有一个类
struct Bar
{
int n;
};
那么指向成员 Bar::n
的指针必须将其类型声明为 int Bar::*
:
int Bar::* p = &Bar::n;
注意int
指的是指针指向的类型,Bar::*
表示“指向Bar
成员的指针” .
现在你的例子的功能,
template<typename _Tp, typename _Class>
struct _Maybe_wrap_member_pointer<_Tp _Class::*> // note no comma here
接受一个模板参数(只有一个!),它表示类 _Class
的成员指针类型,指向 _Tp
类型的非静态数据成员。
这是只有一个模板参数的类模板的模板特化:
template <typename T>
struct _Maybe_wrap_member_pointer
{ };
我们可以像这样使用上面的简单类来实例化特化:
_Maybe_wrap_member_pointer<int Bar::*>
或使用decltype
:
_Maybe_wrap_member_pointer<decltype(&Bar::n)>
在这两种情况下,_Tp
被推导为 int
,_Class
被推导为 Bar
。
关于c++ - <functional> 中奇怪的模板语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15239829/