Flynn1179
Flynn1179

Reputation: 12075

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

Upvotes: 5

Views: 112

Answers (3)

paxdiablo
paxdiablo

Reputation: 881383

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

Upvotes: 4

Max E.
Max E.

Reputation: 1917

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

Upvotes: 0

Ajay
Ajay

Reputation: 18411

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

Upvotes: 0

Related Questions