Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 537
Flynn1179 Avatar asked Oct 11 '22 08:10

Flynn1179


1 Answers

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

like image 53
paxdiablo Avatar answered Nov 02 '22 04:11

paxdiablo