c++ - 如何编写指向函数的函数指针,返回指向函数的函数指针?

标签 c++ function pointers

我想将一个函数的地址赋值给一个函数指针,但是要寻址的函数返回一个与自身具有相同签名的函数指针,导致它以一种我根本无法写出返回类型的方式递归, 对于函数指针甚至函数声明本身...

我想有一种方法可以简化问题,以免造成混淆:

我如何编写一个函数声明,它可以返回一个指向自身(或任何其他具有相同签名的函数)的指针?

????? function(int a){
    // could be this function, or another with the same signature, 
    return arbitraryFunction;  
}

?????(*func)(int) = function;  // same problem as above

编辑:

目前我有一个解决方案,但我不会将其作为答案发布,因为它非常丑陋。它通过简单地返回原始 void* 指针作为返回类型来摆脱递归,并最终采用以下形式:

void* function(int parameter){
    return arbitraryFunction; // of the same signature
}

void*(*func)(int) = function; 
func = reinterpret_cast<void*(*)(int)>(func(42));  // sin

编辑2:

函数指针和常规指针之间的转换似乎是 UB,所以在这种情况下我不能使用 void*...

要回答其中一条评论,这是为了在我的程序中的多个“主”循环之间传递控制,每个循环都有自己的功能。有很多方法可以做到这一点,但是在循环中返回函数指针(或 NULL 以终止程序)似乎像最简单的方法,但我没有预料到指向数据的指针和指向功能地址将彼此不兼容。我认为在这种情况下返回多态函数对象最终将成为更明智的选择。

最佳答案

不要使用void*,因为不能保证void * 可以保存函数指针。您可以使用 void(*)() 作为解决方法:

typedef void(*void_func)();
typedef void_func (*func_type) (int);
void_func arbitraryFunction(int a) {
    // could be this function, or another with the same signature, 
    cout << "arbitraryFunction\n";
    return nullptr;  
}
void_func function(int a) {
    // could be this function, or another with the same signature, 
    return (void_func) arbitraryFunction;  
}
int main() {
    // your code goes here
    func_type f = (func_type) function(0);
    f(0);
    return 0;
}

LIVE

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.

关于c++ - 如何编写指向函数的函数指针,返回指向函数的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809304/

相关文章:

c++ - 使用文件 C++

c++ - 在 C/C++ 中打印所有 ASCII 值

C++ 多线程将模板化的 std::bind 提供给另一个线程

c++ - 收集2 : error: ld returned 1 exit status

function - 函数式编程中的所有纯函数都是连续的吗?

c - 在函数 c 中使用枚举定义全局变量

C指针: Explain the program concept

c - 将结构指针传递给c中的函数

c - 使用结构实例指针取消引用结构实例元素

java - 如何检索 Point2D 的 X 轴和 Y 轴?