问题描述
以下是否合法?
template< typename T >
struct tree_node
{
T t;
std::vector<tree_node> children;
};
注释似乎暗示它不是。
作为未定义行为类型的场景。预期的语义是明确的。如果它是不完整类型的无效使用,那么它应该是编译时错误。
This doesn't strike me as an "undefined behavior" type of scenario. The intended semantics are unambiguous. If it is an invalid usage of an incomplete type then it should be a compile-time error.
这似乎工作正常(我使用了和 - 都使用 -Wall -Werror -std = c ++ 11
)。
In my tests this seems to work fine (I have used both GCC and Clang -- both with -Wall -Werror -std=c++11
).
在语言定义中(在C ++ 17之前),有直接或间接指定为未定义行为的东西,或者只是 / em>
Is there something in the language definition (prior to C++17) that directly or indirectly specifies this as undefined behavior, or is it just under-specified?
请记住,这在结构上非常相似,如下所示:
Keep in mind that this is very similar, structurally, to something like the following:
typedef int T;
struct tree_node;
struct tree_node
{
T t;
tree_node * children;
}
推荐答案
我们有(从N4527,[vector.overview] ,将在C ++ 17中):
Actually, as a result of N4371 we have (from N4527, [vector.overview], will be in C++17):
在此之前,向量
无法使用不完整类型构造( tree_node
那个点),这将是未定义的行为。
Prior to this, vector
could not be constructed with an incomplete type (which tree_node
is at that point), and that would be undefined behavior.
这篇关于类(或结构)通过模板自引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!