Martin Perry Martin Perry - 1 month ago 10
C++ Question

C++ - const vs non const member function - template with function pointers

I have a code, that is havily using templates. One example is this:

template <class MT>
struct class_method_info;

template <class T, class Res, class... Args>
struct class_method_info<Res(T::*)(Args...)>
{
typedef std::tuple<Args&&...> ArgsTuple;
typedef T ClassType;
typedef Res RetVal;
static constexpr std::size_t ArgsCount = sizeof...(Args);
static constexpr bool IsClassMethod = true;
};


This works for the non-const member function pointers.

If I change
Res(T::*)(Args...)
to
Res(T::*)(Args...) const
, I can pass
const
function pointers. However, even if this is working a solution, it messed up my code, because now I have everything doubled and there are a lot of such things.

Is there any other way?

Answer

You can add a specialization for const this, that would inherit most of the implementation from the other one:

template <class MT>
struct class_method_info;

template <class T, class Res, class... Args>
struct class_method_info<Res(T::*)(Args...)>
{
    typedef std::tuple<Args&&...> ArgsTuple;
    typedef T ClassType;
    typedef Res RetVal;
    static constexpr std::size_t ArgsCount = sizeof...(Args);
    static constexpr bool IsClassMethod = true;
    static constexpr bool IsConstThis = false;
};


template <class T, class Res, class... Args>
struct class_method_info<Res(T::*)(Args...) const> : class_method_info<Res(T::*)(Args...)>
{
    static constexpr bool IsConstThis = true;
};

demo