Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can typedef of member function be simplified with helper template classes?

Tags:

c++

I recently found that function pointer syntax can be simplified when using the following helper class:

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

It allows me a pointer to void() as follows:

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

I would like to create a similar utility for to create a typedef to member function pointers. It would allow the following syntax:

struct Foo {
    void bar() {}
};

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

However, I can't figure out the typedef syntax:

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

Can anyone help?

like image 217
StackedCrooked Avatar asked Nov 04 '22 18:11

StackedCrooked


1 Answers

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" );

When the Sig argument is a function type, the resulting type is a pointer to member function, not a pointer to data member. In particular, in this context function types like void() const are valid.

like image 129
Luc Danton Avatar answered Nov 12 '22 10:11

Luc Danton