初始化包含自身向量的结构体 [英] Initialising a struct that contains a vector of itself
问题描述
我有一个菜单系统,我想从常量数据初始化。 MenuItem
可以包含 MenuItems
的向量作为子菜单。但它只工作到一个点。这里是问题的裸骨:
I have a menu system that I want to initialise from constant data. A MenuItem
can contain, as a sub-menu, a vector of MenuItems
. But it only works up to a point. Here are the bare bones of the problem:
#include <vector>
struct S { std::vector<S> v ; } ;
S s1 = { } ;
S s2 = { { } } ;
S s3 = { { { } } } ;
g ++ -std = c ++ 0x
(版本4.4.5)处理 s1
和 s2
,但 s3
返回:
g++ -std=c++0x
(version 4.4.5) copes with s1
and s2
, but s3
comes back with:
prog.cpp:6:22: error: template argument 1 is invalid
(请参见 ideone )。
推荐答案
GMan在他的评论中是正确的:在 S: :v
在您的代码中, S
仍不完整。类型必须是完整的,才能用作STL容器中的值类型。有关详情,请参阅Matt Austern的文章标准库管理员:不完整类型的容器。
GMan is correct in his comment: in the declaration of S::v
in your code, S
is still incomplete. A type must be complete to be usable as the value type in an STL container. For more information see Matt Austern's article "The Standard Librarian: Containers of Incomplete Types."
如果您要切换到可以使用不完整类型的容器,那么代码就可以了。例如,给定以下内容:
If you were to switch to a container that is usable with an incomplete type, then your code is fine. For example, given the following:
#include <initializer_list>
template <typename T>
struct Container
{
Container() { }
Container(std::initializer_list<T>) { }
};
struct S { Container<S> v; };
那么你的初始化应该很好:
then your original initialization should work fine:
S s3 = { { { } } } ;
这也可以工作:
S s4 = { { { { { { { { { { { { { { { { /*zomg*/ } } } } } } } } } } } } } } } };
这篇关于初始化包含自身向量的结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!