Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can structs not be defined in a function declaration in C++11 or higher?

Tags:

People also ask

Can you define a struct inside a function in C?

1. Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.

Can you define a struct in a function?

No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result. Show activity on this post. No, but you can in c++ struct!

Where should structs be declared?

If a struct is declared in a header file in C++, you must include the header file everywhere a struct is used and where struct member functions are defined. The C++ compiler will give an error message if you try to call a regular function, or call or define a member function, without declaring it first.

Can we put function inside struct?

Structure is a UDT in C++ too but you can have functions inside structures. You cannot declare a function in a structure as the structure is itself included in a function i.e. int main() or void main() or in any other function you may declare, and you cannot declare a funtion into another function.


What I am trying to achieve is mainly returning an unnamed struct from a function in C++11. In C++14, I can do this by defining the function inline and having auto as return type, like this:

auto func()
{
    struct
    {
        int member;
    } ret;

    // set ret.member

    return ret;
}

However, C++11 doesn't support deducing the return type of a normal (non-lambda) function, and this only works in C++14 when the definition is done inline.

I tried the following two variations of declaring the struct in the function declaration:

auto func() -> struct { int member; };
struct { int member; } func();

Is this simply impossible to do with C++11? If so, does someone know whether this was disallowed on purpose or just nobody thought of this new use of automatically deduced types (because this only works with the functions return value being assigned to an auto variable)?

And finally, is there any other way to achieve something similar to this? I am aware of std::tuple, but I want to name the values; and in my use case the struct type is definitely only useful as return type of this one function, so why name it?