Recursive C ++ Type Definition

Why is the following code valid? The struct test contains the test vector, so the following code compiles (IDEOne) :

#include <iostream>
#include <vector>

using namespace std;

struct test {
    vector<test> a;
};

int main() {
    // your code goes here
    test t;
    if (t.a.size() > 0)
        return -1;
    else if (t.a[0].a[0].a.size() > 0)
        return 1;
    return 0;
}

How does the compiler handle the structure so that it can be checked for t.a[0].a[0].a.size()? Is there a limit on how often I could repeat .a[0]?


Edit: these questions have an answer that claims that this behavior is undefined: C ++ recursive type definitions are possible, in particular, can you put the vector <T> in the definition of T?

=> This is confusing

=> maybe my question is a duplicate

+4
source share
1 answer

vector<T>, , T, T . , , :

struct test {
    test* start;
    test* end;
};

, - .

: test vector<T>, array<T,Size> pair<T,K> :

struct broken1 {
    array<broken1,3> a; // Does not compile
};
struct broken2 {
    pair<broken2,broken2> p; // Does not compile
};
+2

Source: https://habr.com/ru/post/1671591/


All Articles