Question

I have a class:

struct C {
    int F(int, char) { return 0; }
};

and I need to create an std::function, which will call the C::F function for a variable c:

C c;
std::function<int(int, char)> f;
...
f = std::bind(&C::F, &c, _1, _2);

but if the signature of the function is changed I need to change the std::function as well.

so I would like to not duplicate the signature:

C c;
std::function<delete_class<decltype(&C::F)>::type> f;
...
f = std::bind(&C::F, &c, _1, _2);

where delete_class is some magic helper, which changes type int(C::*)(int, char) to int(int, char).

I suspect, that I can implement it with the help of boost::mpl or boost::function_types, but I couldn't do it.

Can someone, who has experience, show me how to do it?

PS. VS 2010

Was it helpful?

Solution

If you need a type trait delete_class that works as you desire, this one should do the job:

template<typename S>
struct delete_class;

template<typename R, typename C, typename... Ts>
struct delete_class<R (C::*)(Ts...)>
{
    using type = R(Ts...);
};

The following assertion will then be satisfied:

static_assert(
    std::is_same<delete_class<decltype(&C::F)>::type, 
    int(int, char)
    >::value, "!");

And you could then use delete_class<> the way you propose:

std::function<delete_class<decltype(&C::F)>::type> f;
C c;
f = std::bind(&C::F, &c, _1, _2);

Here is a live example.

EDIT:

If you are limited to VC10 support (i.e. no variadic templates), you will have to define several partial specializations of the delete_class primary template:

template<typename S>
struct delete_class;

template<typename R, typename C>
struct delete_class<R (C::*)()>
{
    typedef R(type)();
};

template<typename R, typename T>
struct delete_class<R (C::*)(T)>
{
    typedef R(type)(T);
};

template<typename R, typename T, typename U>
struct delete_class<R (C::*)(T, U)>
{
    typedef R(type)(T, U);
};

template<typename R, typename T, typename U, typename V>
struct delete_class<R (C::*)(T, U, V)>
{
    typedef R(type)(T, U, V);
};

// And so on...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top