MFH
MFH

Reputation: 1734

Deduce type from (member) function

Is there a simple way to deduce the "type" of a member function? I would like to deduce the type of the following (member) function:

struct Sample {
  void func(int x) { ... }
};

void func(int x) { ... }

To the following type (to be used in std::function):

void(int)

I'm looking for a solution that does support a variable count (not varargs!) of arguments...

EDIT - Example:

I'm looking for an expression similar to decltype - let's call it functiontype - that has the following semantics:

functiontype(Sample::func) <=> functiontype(::func) <=> void(int)

functiontype(expr) should evaluate to a type that is compatible with std::function.

Upvotes: 0

Views: 186

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126422

Does this help?

#include <type_traits>
#include <functional>

using namespace std;

struct A
{
    void f(double) { }
};

void f(double) { }

template<typename T>
struct function_type { };

template<typename T, typename R, typename... Args>
struct function_type<R (T::*)(Args...)>
{
    typedef function<R(Args...)> type;
};

template<typename R, typename... Args>
struct function_type<R(*)(Args...)>
{
    typedef function<R(Args...)> type;
};

int main()
{
    static_assert(
        is_same<
            function_type<decltype(&A::f)>::type, 
            function<void(double)>
            >::value,
        "Error"
        );

    static_assert(
        is_same<
            function_type<decltype(&f)>::type, 
            function<void(double)>
            >::value,
        "Error"
        );
}

Upvotes: 3

Related Questions