【问题标题】:Can typedef of member function be simplified with helper template classes?可以使用帮助模板类简化成员函数的 typedef 吗?
【发布时间】:2011-07-09 18:25:34
【问题描述】:

我最近发现使用以下帮助类可以简化函数指针语法:

template<typename Sig>
struct Fun {
    typedef Sig* Ptr;
};

它允许我指向void(),如下所示:

typedef Fun<void()>::Ptr fun_ptr;
fun_ptr f = foo;

我想创建一个类似的实用程序来为成员函数指针创建 typedef。它将允许以下语法:

struct Foo {
    void bar() {}
};

typedef MemFun<Foo, void()>::Ptr bar_type;
bar_type b = &Foo::bar;

但是,我无法弄清楚 typedef 语法:

template<class T, typename Sig>
struct MemFun {
    // How to use T and Sig to create member function typedef?
};

谁能帮忙?

【问题讨论】:

  • std::function 有问题吗?或者boost::function,如果你的工具链是古老的......这一切都已经被发明了,很久以前。

标签: c++


【解决方案1】:
template<typename T, typename Sig>
struct convenience {
    typedef Sig T::*type;
};

struct test {
    void member() {}
    void cmember() const {}
};

static_assert( std::is_same<
        convenience<test, void()>::type
        , decltype(&test::member)
    >::value, "Oops" );

static_assert( std::is_same<
        convenience<test, void() const>::type
        , decltype(&test::cmember)
    >::value, "Oops" );

当Sig 参数是函数类型时,结果类型是指向成员函数的指针,而不是指向数据成员的指针。特别是,在这种情况下,void() const 这样的函数类型是有效的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多