vendredi 21 juillet 2023

Generation a pointer-to-member function or a member matching another declaration

This particular method was used in code to bridge a generic algorithm and some generated class implementations (represented here by class B):

// A class generated by outside source
struct B {
    void foo(int);
    void foo();

    int bar();
    int bar() const;

    float blah(int) const;
};

#define DECLARE_METHOD_TYPE(TName, CName, Func)    \
     template<typename ...Args>                    \
     using TName = decltype(                       \
     std::declval<CName>().Func(std::declval<Args>() ...)) \
         (CName::*) (Args...)

#define METHOD_PTR(TName, ... ) static constexpr TName<__VA_ARGS__>

// A bridge
struct A 
{
    DECLARE_METHOD_TYPE(FooPtr, B, foo);

    // need both declaration
    DECLARE_METHOD_TYPE(BarPtr, B, bar);
    DECLARE_METHOD_TYPE(BarPtrConst, B, bar) const;

    // must be const
    DECLARE_METHOD_TYPE(BlahPtrConst, B, blah) const;

    METHOD_PTR(FooPtr, int) b_foo_n = &B::foo;
    METHOD_PTR(FooPtr)      b_foo   = &B::foo;

    METHOD_PTR(BarPtr)      b_bar   = &B::bar;
    METHOD_PTR(BarPtrConst) b_cbar  = &B::bar;

    // must be exact
    METHOD_PTR(BlahPtrConst, int) b_blah = &B::blah;
};

Is there w way to declare each pointer in a single statement? main proble there is that the pointer type is a template and I need a unique typename for it.

Or is there a way to create a macro that generates member function which would call B's member (like a visitor). I think, I can declare such function, but I cannot define it.

Aucun commentaire:

Enregistrer un commentaire