c++ - <functional> 中奇怪的模板语法

标签 c++ templates c++11 std-function stdbind

我一直在查看 gcc-4.7.2 中 std::functionstd::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/

相关文章:

c++ - 当包含在另一个 vector 中时如何使用 vector 包装类?

c++ - 我们可以在 C++ 中重载 main() 函数吗?

c++ - 简单的类 MPL 类型映射模板

c++ - 模板化结构的括号括起来的初始值设定项列表

c++ - 在 C++11 lambda 中按引用捕获引用

c++ - 模板循环依赖 - 不同文件中的单独类

c++ - 使用 RPN 形式的函数

c++ - G++ 在 Ubuntu 中找不到 <iostream.h>

c++ - 模板方法中迭代器参数的问题

C++11 声明 `::T i` ?