Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c++ - How to allow templated functor work on both member and non-member functions

I got this logging templated functor

template<typename RetType, typename Arg1Type, typename Class>

class Logger
{  public:

RetType operator()(Arg1Type s, ...)
{
    if(func != 0 && parser != 0)
        return (parser->*func)(s);
    else if(nfunc != 0)
        return nfunc(s);
    return RetType();
}

Logger& operator=(RetType(*fun)(Arg1Type s, ...))
{
    func = fun;
    return *this;
}

void Bind(Class* pars, RetType(Class::*fun)(Arg1Type s,...))
{
    parser = pars;
    func = fun;
    nfunc = 0;
}

void Bind(RetType(*fun)(Arg1Type s,...))
{
    nfunc = fun;
    func = 0;
    parser = 0;
}

private:
    RetType (Class::*func)(Arg1Type s, ...); //member class method
    RetType(*nfunc)(Arg1Type s, ...);        //non-member class method
    Class* parser;
};

Now I can call this class using something like this :

Logger<int, const char*, WinLogger > p1;
WinLogger w1;
p1.Bind(&w1, &WinParser::Log);
p1("log");

But when I want to bind it to any non-member function using:

Logger<int, const char*, void> 

the compiler complains that: 'Class': must be a class or namespace when followed by '::'. Because he cannot fit the void type to the first Bind method. But if create the logger with any DummyClass its ok.

Logger<int, const char*, DummyClass> p2;
p2.Bind(printf);
p2("printf called");

Which is very ugly. Is there a workaround this?

I know I should probably be using boost::function etc. but I wanted to exactly learn how functon pointers and functors works so I decided to not use it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's possible to define a single Logger<int, const char*> type, which may call either a member or a non-member function of any class. To do this, you'll need to remove the Class parameter from Logger and instead store an opaque object pointer [void*] and a function pointer that accepts an opaque object [R (*func)(void* object, A a)].

This solves the problem in your question by making Logger unaware of what kind of function it contains; whether it be a a non-member, a member of class X, or a member of class Y.

You can implement this using a technique I developed for C++03 which involves generating wrapper functions (aka 'thunks') to call the member and non-member functions through a function pointer known at compile-time. You can think of this as a cut-down specialised version of std::function in C++11 or Delegate in C#.

template<typename F>
struct FunctionTraits;

template<typename R, typename C, typename A>
struct FunctionTraits<R (C::*)(A)> // matches a pointer to member function
{
    typedef R RetType;
    typedef C Class;
    typedef A Arg1Type;
};

template<typename R, typename A>
struct FunctionTraits<R (*)(A)> // matches a pointer to function
{
    typedef R RetType;
    typedef A Arg1Type;
};

template<typename RetType, typename Arg1Type>
class Logger
{
    typedef RetType(*Func)(void*, Arg1Type);
public:

    Logger(void* pars, Func func) : pars(pars), func(func)
    {
    }

    RetType operator()(Arg1Type a) const
    {
        // call the function with the opaque object
        return func(pars, a);
    }

private:

    Func func; // a pointer to a function accepting an opaque object
    void* pars; // a pointer to an opaque object
};

template<typename F, F p>
typename FunctionTraits<F>::RetType callMember(void* c, typename FunctionTraits<F>::Arg1Type a)
{
    // restore the type of the object
    return (static_cast<typename FunctionTraits<F>::Class*>(c)->*p)(a);
}

template<typename F, F p>
Logger<typename FunctionTraits<F>::RetType, typename FunctionTraits<F>::Arg1Type>
    makeLogger(typename FunctionTraits<F>::Class* pars)
{
    typedef typename FunctionTraits<F>::RetType RetType;
    typedef typename FunctionTraits<F>::Arg1Type Arg1Type;
    // generates a 'thunk' function which calls the member 'p'
    return Logger<RetType, Arg1Type>(pars, &callMember<F, p>);
}

template<typename F, F p>
typename FunctionTraits<F>::RetType callNonMember(void*, typename FunctionTraits<F>::Arg1Type a)
{
    // the first parameter is not used
    return (p)(a);
}

template<typename F, F p>
Logger<typename FunctionTraits<F>::RetType, typename FunctionTraits<F>::Arg1Type>
    makeLogger()
{
    typedef typename FunctionTraits<F>::RetType RetType;
    typedef typename FunctionTraits<F>::Arg1Type Arg1Type;
    // generates a 'thunk' function which calls the non-member 'p'
    return Logger<RetType, Arg1Type>(0, &callNonMember<F, p>);
}

int log(const char*);

struct Parser
{
    int log(const char*);
};

struct OtherParser
{
    int log(const char*);
};

int main()
{
    Logger<int, const char*> nonmember = makeLogger<decltype(&log), &log>();
    int result1 = nonmember("nonmember"); // calls log("nonmember");

    Parser pars;
    Logger<int, const char*> member = makeLogger<decltype(&Parser::log), &Parser::log>(&pars);
    int result2 = member("member"); // calls pars.log("member");

    OtherParser other;
    Logger<int, const char*> member2 = makeLogger<decltype(&OtherParser::log), &OtherParser::log>(&other);
    int result3 = member2("member2"); // calls other.log("member2");
}

Despite using void*, this technique is both type-safe and standard-compliant.

In contrast with std::function, the generated functions are able to inline the calls through the member/non-member pointer because the pointer is known at compile time.

EDIT: The above example uses C++11's decltype to automatically determine the type of a function pointer, but this is not essential - I can offer a C++98 compatible technique that achieves the same thing:

template<typename F>
struct NonMemberHelper
{
    template<F p>
    static Logger<typename FunctionTraits<F>::RetType, typename FunctionTraits<F>::Arg1Type>
        apply()
    {
        return makeLogger<F, p>();
    }
};

template<typename F>
NonMemberHelper<F> makeNonMemberHelper(F)
{
    return NonMemberHelper<F>();
}

template<typename F>
struct MemberHelper
{
    template<F p>
    static Logger<typename FunctionTraits<F>::RetType, typename FunctionTraits<F>::Arg1Type>
        apply(typename FunctionTraits<F>::Class* pars)
    {
        return makeLogger<F, p>(pars);
    }
};

template<typename F>
MemberHelper<F> makeMemberHelper(F)
{
    return MemberHelper<F>();
}

#define MAKE_LOGGER_NONMEMBER(func) makeNonMemberHelper(func).apply<(func)>()
#define MAKE_LOGGER(func, pars) makeMemberHelper(func).apply<(func)>(pars)

int main()
{
    Logger<int, const char*> callNonMember = MAKE_LOGGER_NONMEMBER(&log);
    int result1 = callNonMember("nonmember"); // calls log("nonmember");

    Parser pars;
    Logger<int, const char*> callMember = MAKE_LOGGER(&Parser::log, &pars);
    int result2 = callMember("member"); // calls pars.log("member");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...