ISO C ++ prohibits casting between a function pointer and an object pointer

I want to have a class that could store a function pointer as its fields, and a pointer to the storage structure - these are the arguments. The interface of this object will be a call to method () with no arguments, but passing the stored arguments to the above function. The family of such classes for different types of arguments and counters will have a common abstract ancestor with a virtual call.

At the moment, I have the following code that works, although adding the -pedantic option to g ++ gives errors:

class Function {
    protected:
    void *data;
    void *function;
    public:
    virtual void call() = 0;
};

class SingleArgumentFunction : public Function {
    public:
    SingleArgumentFunction( void (*f)(int), int i ) {
        int *icpy = new int(i);
        function = (void*) f;
        data = (void*) icpy;
    }
    ~SingleArgumentFunction() { delete (int*)data; }
    inline void call() {
        ( *((void (*)(int))function) )( *(int*)data );
    }
};

The error that I get corresponds to the name:

warning: ISO C++ forbids casting between pointer-to-function and pointer-to-object

How to deal with this?

+5
source share
2 answers

, . , void(*)().

C99 [6.2.5/27]:

void , . . . . .

C99 [6.3.2.3/8]:

; .

, SO-.


, , std::function+std::bind.

std::function< void() > f;
f = std::bind( &some_function_that_takes_an_int, 42 );

f(); // look ma! no arguments
+9

API, void*, , __extension__, . gcc-specific, , ..:

#ifdef __GNUC__
__extension__
#endif
the_statement_that_includes_the_cast;

http://trac.osgeo.org/qgis/ticket/234.

+1

All Articles