开发者

Is it possible to specify a function directly in a struct declaration in C++?

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 functio开发者_如何转开发n 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.


If you mean something like:

Foo list[] = {
    { 0, int (*)(int x) { return x;} },
    { 1, 0 } // no func for this.
};

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:

Foo list[] = {
    { 0, [](int x) { return x; } },
    { 1, 0                       }
};

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).


In C++0x you may use lambdas to keep your data and code together, but that would make code hard to read and maintain.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜