是否可以在 C++ 的结构声明中直接指定函数?
例如:
struct Foo
{
int bar;
int (*baz)(int);
};
int testFunc(int x)
{
return x;
}
Foo list[] = {
{ 0, &testFunc },
{ 1, 0 } // no func for this.
};
在这个例子中,我宁愿将函数直接放入 list[] 初始值设定项中,而不是使用指向其他地方声明的函数的指针;它将相关的代码/数据保存在同一位置。
有办法做到这一点吗?我尝试了所有我能想到的语法,但无法让它工作。
For example:
struct Foo
{
int bar;
int (*baz)(int);
};
int testFunc(int x)
{
return x;
}
Foo list[] = {
{ 0, &testFunc },
{ 1, 0 } // no func for this.
};
In this example, I'd rather put the function directly into the list[] initializer rather than using a pointer to a function declared elsewhere; it keeps the related code/data in the same place.
Is there a way of doing this? I tried every syntax I could think of and couldn't get it to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你的意思是:
那么,不,这是不可能的。您正在谈论 匿名函数,C++ 尚不支持(截至 2011 年 8 月) 。
C++0x 添加了对 lambda 函数 的支持,这几乎是同样的事情,你的语法可能是这样的:
但是,如果你的目的只是让代码和数据保持接近,那么就让它们保持接近(相同的 C 源文件,代码紧接在数据之前) 。
If you mean something like:
then, no, it's not possible. You're talking about anonymous functions, something C++ doesn't yet support (as of August 2011).
C++0x is adding support for lambda functions, which is pretty much the same thing and your syntax would probably be something like:
However, if your intention is simply to keep the code and data in close proximity, then just keep them in close proximity (the same C source file, with the code immediately preceding the data).
在 C++0x 中,您可以使用 lambda 将数据和代码保存在一起,但这会使代码难以阅读和维护。
In C++0x you may use lambdas to keep your data and code together, but that would make code hard to read and maintain.
您正在寻找的是 C 或 C++ 中不存在的匿名函数(尽管 Clang非官方支持,将在C++0x中添加。)
What you're looking for is anonymous functions which don't exist in C or C++ (although Clang supports it unofficially, and it will be added in C++0x.)