简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM