ISO C禁止在指向函数的指针和指向对象的指针之间进行转换

我希望有一个类能够保持其字段指向函数的指针和指向结构保持的指针是参数.该对象的接口是一个方法call(),它不带参数,但将保存的参数传递给上面提到的函数.针对不同参数类型和计数的这类类的一族将具有共同的抽象祖先,其中调用是虚拟的.

至于现在我有以下代码可以工作,虽然添加-pedantic选项g产生错误:

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 );
    }
};

我得到的错误是标题所示:

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

怎么处理?

最佳答案
不要将指向函数的指针转换为指向对象的指针,它们不能保证具有相同的大小.您将能够通过使用void(*)()函数指针来解决此问题.

C99 [6.2.5 / 27]:

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

C99 [6.3.2.3/8]:

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.

参考文献取自this other SO answer.

顺便说一下,您似乎正在尝试重新创建std :: function std :: bind.

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

f(); // look ma! no arguments

转载注明原文:ISO C禁止在指向函数的指针和指向对象的指针之间进行转换 - 代码日志