Pass between function pointers

I am currently using a timer / callback system using don Clagston's fastdelegates. (see http://www.codeproject.com/KB/cpp/FastDelegate.aspx )

Here is the starting code:

struct TimerContext
{
};

void free_func( TimerContext* )
{
}

struct Foo
{
    void member_func( TimerContext* )
    {
    }
};

Foo f;
MulticastDelegate< void (TimerContext*) > delegate;

delegate += free_func;
delegate += bind( &Foo::member_func, &f );

Ok, but now I want the user to be able TimerContextto store and send subclasses of their own structures in callbacks. The goal here is to prevent the user from disconnecting himselfTimerContext

struct TimerContext
{
};

struct MyTimerContext : TimerContext
{
    int user_value;
};

void free_func( TimerContext* )
{
}

void free_func2( MyTimerContext* )
{
}

struct Foo
{
    void member_func( TimerContext* )
    {
    }

    void member_func2( MyTimerContext* )
    {
    }
};

Foo f;
MulticastDelegate< void (TimerContext*) > delegate;

delegate += free_func;
delegate += free_func2;
delegate += bind( &Foo::member_func,  &f );
delegate += bind( &Foo::member_func2, &f );

As you may have guessed, GCC will not let me do this :)

error: invalid conversion from `void (*)(MyTimerContext*)' to `void (*)(TimerContext*)'
error:   initializing argument 1 of `delegate::Delegate<R ()(Param1)>::Delegate(R (*)(Param1)) [with R = void, Param1 = TimerContext*]'

So now my question is: If I close the cast with reinterpret_cast, it will work, but will it be safe?

PS: These are critical critical callbacks, heavy virtual-oriented solutions are considered impracticable: /

+3
3

++ Standard 13.4/7, :

( 4) - . , B D,

D* f();
B* (*p1)() = &f;  // error
void g(D*);
void (*p2)(B*) = &g;  // error

, , - boost::function, , .

+5

, , , .

void(*)(Derived*) void(*)(Base*), . , , , Derived * Base * . . , , . : ahread.

, , void(*)(Derived1*) void(*)(Base*) ( ), , , Derived1 * Derived2 *, Derived1 Derived2 .

0

reinterpret_cast , "" "" . , , .

, , , :

  • , = > .

  • = > , ( exec ..).

0

Source: https://habr.com/ru/post/1720485/


All Articles