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

For instance:

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 would rather put the function directly in the initializer of the list [] instead of using a pointer to a function declared elsewhere; it saves the corresponding code / data in the same place.

Is there any way to do this? I tried every syntax that I could think of and could not get it to work.

+5
source share
3 answers

If you mean something like:

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

then no, it is impossible. You are talking about anonymous functions , something C ++ does not support yet (as of August 2011).

++ 0x -, , , , :/p >

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

, , ( C , ).

+4

++ 0x lambdas , .

0

What you are looking for are anonymous functions that do not exist in C or C ++ (although Clang supports it informally and this will be added in C ++ 0x.)

0
source

All Articles