Ste*_*mer 2 c++ templates stdbind c++11 std-function
我一直在寻找的源代码std::function,并std::bind在GCC-4.7.2,和整个使用成员函数指针,我有些不明白的语法来了.
我不明白的是_Maybe_wrap_member_pointer:
template<typename _Tp, typename _Class>
struct _Maybe_wrap_member_pointer<_Tp _Class::*> // note no comma here
Run Code Online (Sandbox Code Playgroud)
为什么_Tp和之间没有逗号_Class::*?
由于成员函数void foo::bar()(在下面我示例应用程序),你会_Tp和_Class::*决心吗?
下面是我的示例应用程序,它绑定成员函数指针和对象.(我已经提取了与std::bind成员函数的特化/内部相关的源代码)
#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);
}
Run Code Online (Sandbox Code Playgroud)
这确实是用于将成员指针类型指定为模板参数的语法.
假设你有一个班级
struct Bar
{
int n;
};
Run Code Online (Sandbox Code Playgroud)
那么指向该成员的指针必须Bar::n将其类型声明为int Bar::*:
int Bar::* p = &Bar::n;
Run Code Online (Sandbox Code Playgroud)
注意,int指的是指针指向的类型,Bar::*意思是"指向成员的指针Bar".
现在你的例子的功能,
template<typename _Tp, typename _Class>
struct _Maybe_wrap_member_pointer<_Tp _Class::*> // note no comma here
Run Code Online (Sandbox Code Playgroud)
接受一个模板参数(只有一个!),它表示类的成员指针类型,指向类型的_Class非静态数据成员_Tp.
这是一个模板特具有类模板的只有一个模板参数:
template <typename T>
struct _Maybe_wrap_member_pointer
{ };
Run Code Online (Sandbox Code Playgroud)
我们可以使用上面的简单类来实例化特化,如下所示:
_Maybe_wrap_member_pointer<int Bar::*>
Run Code Online (Sandbox Code Playgroud)
或使用decltype:
_Maybe_wrap_member_pointer<decltype(&Bar::n)>
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,_Tp都是推导出来的int,并且_Class是推导出来的Bar.