vlucki
vlucki

Reputation: 49

Const and non-const function as template parameter argument

I've been looking to deepen my understanding of templates and function pointers by creating a very simple event/callback system. I got to a point where I'd like to execute a given function regardless of it's constness in a more... "template-y/generic" way.

Currently there are two wrappers, one for non-const and one for const functions, which works well enough but just seems wrong since they are basically identical.

So here's a section of what I currently have:

Non-Const function wrapper

template<typename CallerType, typename ReturnType, typename ...Args>
    class RegularMemberFunctionWrapper : public MemberFunctionWrapper<CallerType, ReturnType, Args...>
    {
    private:
        ReturnType(CallerType::* funcPtr)(Args...);
    }

Const function wrapper

template<typename CallerType, typename ReturnType, typename ...Args>
    class ConstMemberFunctionWrapper : public MemberFunctionWrapper<CallerType, ReturnType, Args...>
    {
    private:
        ReturnType(CallerType::*funcPtr) (Args...) const;
    }

Ideally, I'd like to have only the parent "MemberFunctionWrapper", where I'd define via a template parameter whether the function is const or not.

template<typename CallerType, typename FunctionSignature, typename ...Args>
    MemberFunctionWrapper
    {
    private:
        FunctionSignature *funcPtr;
    }

Is something like this even possible with templates?

I saw some examples online where one template argument would define a type used by another (eg. template<typename T, T T2>) so maybe there's something to it? Perhaps what I want is not a class template, but function templates called by the derived classes (hence achieving the objective of eliminating code duplication)?

Please enlighten me.

Upvotes: 0

Views: 379

Answers (1)

Jarod42
Jarod42

Reputation: 217085

Not sure it it what you want, but you might have:

template<typename Sig>
class Wrapper
{
private:
    Sig funcPtr;
};

and so, possible usages such as:

Wrapper<void (C::*) (int) const> w1;
Wrapper<void (C::*) (int)> w2;

Demo

Upvotes: 1

Related Questions