C语言 返回函数指针类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20617067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning function pointer type
提问by S E
Often I find the need to write functions which return function pointers. Whenever I do, the basic format I use is:
我经常发现需要编写返回函数指针的函数。每当我这样做时,我使用的基本格式是:
typedef int (*function_type)(int,int);
function_type getFunc()
{
function_type test;
test /* = ...*/;
return test;
}
However this can get cumbersome when dealing with a large number of functions so I would like to not have to declare a typedef for each one (or for each class of functions)
然而,这在处理大量函数时会变得很麻烦,所以我不想为每个函数(或每类函数)声明一个 typedef
I can remove the typedef and declare the local variable returned in the function as:
int (*test)(int a, int b);making the function body look like this:
我可以删除 typedef 并将函数中返回的局部变量声明为:
int (*test)(int a, int b);使函数体看起来像这样:
{
int (*test)(int a, int b);
test /* = ...*/;
return test;
}
but then I do not know what to set for the return type of the function. I have tried:
但后来我不知道该为函数的返回类型设置什么。我试过了:
int(*)(int,int) getFunc()
{
int (*test)(int a, int b);
test /* = ...*/;
return test;
}
but that reports a syntax error. How do I declare the return type for such a function without declaring a typedef for the function pointer. Is it even possible? Also note that I am aware that it seems like it would be cleaner to declare typedefs, for each of the functions, however, I am very careful to structure my code to be as clean and easy to follow as possible. The reason I would like to eliminate the typedefs is that they are often only used to declare the retrieval functions and therefore seem redundant in the code.
但这会报告语法错误。如何在不为函数指针声明 typedef 的情况下声明此类函数的返回类型。甚至有可能吗?另请注意,我知道对于每个函数声明 typedef 似乎更清晰,但是,我非常小心地将代码结构化为尽可能干净且易于遵循。我想消除 typedef 的原因是它们通常只用于声明检索函数,因此在代码中显得多余。
回答by Eric Postpischil
int (*getFunc())(int, int) { … }
That provides the declaration you requested. Additionally, as ola1olssonnotes, it would be good to insert void:
这提供了您要求的声明。此外,正如ola1olsson指出的那样,最好插入void:
int (*getFunc(void))(int, int) { … }
This says that getFuncmay not take any parameters, which can help avoid errors such as somebody inadvertently writing getFunc(x, y)instead of getFunc()(x, y).
这表示getFunc可能不带任何参数,这可以帮助避免错误,例如有人无意中写入getFunc(x, y)而不是getFunc()(x, y).
回答by yosim
You can probably do something like:
您可能可以执行以下操作:
int foo (char i) {return i*2;}
int (*return_foo()) (char c)
{
return foo;
}
but god, I hope I'll never have to debug you code....
但是上帝,我希望我永远不必调试您的代码....
回答by Dmitry
ill leave this here since it was a bit trickier than answers already given, as it takes a function pointer
我把它留在这里,因为它比已经给出的答案有点棘手,因为它需要一个函数指针
(int (__cdecl *)(const char *))
(int (__cdecl *)(const char *))
and returns a function pointer
并返回一个函数指针
(int (__cdecl *)(const char *))
(int (__cdecl *)(const char *))
#include <stdio.h>
int (*idputs(int (*puts)(const char *)))(const char *) {
return puts;
}
int main(int argc, char **argv)
{
idputs(puts)("Hey!");
return 0;
}
回答by duncan
While wrapping some C code in C++ classes, I had the same desire as the original poster: return a function pointer from a function without resorting to typedef'ing the function pointer prototype. I hit a problem with C++ constcorrectness which I thought was worth sharing, even if it's a little off-topic (C++) but it does relate directly to the original question: the syntax for returning a C function pointer without resorting to a typedef.
在 C++ 类中包装一些 C 代码时,我有与原始海报相同的愿望:从函数返回一个函数指针,而不必求助于typedef函数指针原型。我遇到了 C++const正确性的问题,我认为值得分享,即使它有点题外话(C++),但它确实与原始问题直接相关:返回 C 函数指针而不诉诸typedef.
The code below defines a class Awhich stores a function pointer and exposes it to the outside world through the get_f()call. This is the function that should return a function pointer without a typedef.
下面的代码定义了一个类A,该类存储一个函数指针并通过get_f()调用将其暴露给外界。这是应该返回不带 的函数指针的函数typedef。
The point (which stumped me for some time) was how to declare that get_f()was a constfunction, i.e. it wouldn't alter A.
重点(让我难住了一段时间)是如何声明它get_f()是一个const函数,即它不会改变A。
The code contains 2 variants: the first uses a typedef for the function pointer prototype, whilst the second writes everything out in full. The #ifswitches between the two.
代码包含两个变体:第一个为函数指针原型使用 typedef,而第二个则完整地写出所有内容。的#if两个之间切换。
#include <iostream>
int my_f(int i)
{
return i + 1;
}
#if 0 // The version using a typedef'ed function pointer
typedef int (*func_t)(int);
class A
{
public:
A(func_t f) : m_f(f) {}
func_t get_f() const { return m_f; }
private:
func_t m_f;
};
int main(int argc, char *argv[])
{
const A a(my_f);
std::cout << "result = " << a.get_f()(2) << std::endl;
}
#else // The version using explicitly prototyped function pointer
class A
{
public:
A(int (*f)(int)) : m_f(f) {}
int (*get_f() const)(int) { return m_f; }
private:
int (*m_f)(int);
};
int main(int argc, char *argv[])
{
const A a(my_f);
std::cout << "result = " << a.get_f()(2) << std::endl;
}
#endif
The expected/desired output is:
预期/期望的输出是:
result = 3
The key point is the position of the constqualifier in the line:
关键是const限定符在行中的位置:
int (*get_f() const)(int) { return m_f; }
回答by NicoM
This is a stupid example, but it's simple and it does not give errors. It's just about declaring static functions:
这是一个愚蠢的例子,但它很简单,而且不会出错。这只是关于声明静态函数:
#include <stdio.h>
#include <stdlib.h>
void * asdf(int);
static int * hjkl(char,float);
main() {
int a = 0;
asdf(a);
}
void * asdf(int a) {return (void *)hjkl; }
static int * hjkl(char a, float b) {int * c; return c;}
回答by Raffaele Rossi
I think you've got three options:
我认为你有三个选择:
- Stick with typedef. At the end of the day, it's typedef's job.
- Return void* and the casting it.
- Reconsider your software architecture. Perhaps you could share with us what you're trying to achieve and see if we can point you toward a better direction.
- 坚持使用typedef。归根结底,这是 typedef 的工作。
- 返回 void* 和铸造它。
- 重新考虑您的软件架构。也许您可以与我们分享您正在努力实现的目标,看看我们是否可以为您指明更好的方向。
回答by JiaHao Xu
You can write the following code(It only works in C++11 and above):
您可以编写以下代码(仅适用于 C++11 及更高版本):
//C++11
auto func(...) {
int (*fptr)(...) ret = ...
//Do sth.
return ret;//C++11 compiler will automatically deduce the return type for you
}
Or, if you do not like automatic return type deduction, you can specified the type at the end of the function(Same as above, only in C++11 and above):
或者,如果你不喜欢自动返回类型推导,你可以在函数末尾指定类型(同上,仅在 C++11 及以上):
//C++11
auto func(...) -> int (*)(...) { /* Do sth. */ }

