Adding const support to our delegate

Our delegate currently cannot take a member function marked as const as we have not provided our delegate with a wrapper capable of doing so. For example, our heroes' attack() function currently looks like this:

class spiderman
{
public:
bool attack(int x, int)
{
return x == 0 ? true : false;
}
};

We would, however, like our hero attack() functions to look like the following since they do not modify any private member variables:

class spiderman
{
public:
bool attack(int x, int) const
{
return x == 0 ? true : false;
}
};

To support this change, we must create a wrapper that supports this, shown as follows:

template<
typename T,
typename RET,
typename... ARGS
>
class wrapper_const :
public base<RET, ARGS...>
{
T m_t{};
RET (T::*m_func)(ARGS...) const;

public:

wrapper_const(RET (T::*func)(ARGS...) const) :
m_func{func}
{ }

RET func(ARGS... args) override
{
return std::invoke(m_func, &m_t, args...);
}
};

As shown in the preceding, this wrapper is the same as our previous wrapper with the difference being that the function signature that we store has an added const instance. For the delegate to use this additional wrapper, we must also provide an additional delegate constructor as follows:

    template<typename T>
delegate(RET (T::*func)(ARGS...) const) :
m_wrapper{
std::make_unique<wrapper_const<T, RET, ARGS...>>(func)
}
{ }

This means we will also need an additional user-defined type deduction guide, as follows:

template<
typename T,
typename RET,
typename... ARGS
>
delegate(RET(T::*)(ARGS...) const) -> delegate<RET(ARGS...)>;

With these modifications, we can now support member functions marked with const.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset