简体   繁体   中英

Can I create a std::vector of a struct without defining the struct first?

Instead of:

struct MyStruct{
    ...
};

std::vector<MyStruct> myVec;

Can I do something like:

std::vector<struct MyStruct {...}> myVec;

or even, since I don't need a name for this struct as I'm only using it inside this vector:

std::vector<struct {...}> myVec?

I'm using C++ for many years and I don't think it's possible. I think it would be nice though...

Or is there a way?

Last I checked, any type stored in a standard container (dunno why you reference STL, which is similar but different and in any case ambiguous!) must be complete. A (forwand-)declared type is not complete. If you want to know, please check the standard of the version you are using or at least mention that here.

Concerning the inline declaration of a struct in a template parameter, eg g++ says "types may not be defined in template arguments" when I try that. I can't give you a convincing reason why that shouldn't work. After all, all containers supply an element_type alias and with auto from C++ 11 that shouldn't be a problem in general.

Both of the previous answers are correct - you cannot define a vector of something of incomplete type.

However, you can declare one - with the requirement that when you define it the type must be complete.

struct Foo; // forward declaration
using FooV = std::vector<Foo>; // declaration

struct Foo { int val; }; // definition
FooV v; // define a vector - all is well.

No , you cannot do that when you declare an actual variable or type, as C++ is a staticly typed language. The C++ construct to allow for general types are templates, ie

template<typename T>
using myVec = std::vector<T>;

which you can use directly, eg

struct someStruct { /* ... */ };
myVec<someStruct> foo;

or in some template code

template<typename T>
T bar(myVec<T> const&vec)
{
    /* ... */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM