Antoine Morrier
Antoine Morrier

Reputation: 4078

std::variant and incomplete type: how does it work?

I do understand that std::variant works with incomplete type. However, I don't understand how it can works because, in my understanding, std::variant must need the maximum size of the types it holds.

So, why does this code does not compile with s1 and s2. How can make it works like std::variant?

#include <variant>
#include <vector>
#include <type_traits>
#include <typeinfo>
#include <iostream>

struct Rect;
struct Circle;

using Shape = std::variant<Rect, Circle>;

template<typename C>
struct S {static constexpr auto s = sizeof(C);};

constexpr auto s1 = S<Rect>::s;
constexpr auto s2 = sizeof(Rect);

struct Circle{};
struct Rect{
    std::vector<Shape> shapes;
};

int main() {}

Upvotes: 3

Views: 1644

Answers (1)

eerorika
eerorika

Reputation: 238311

I do understand that std::variant works with incomplete type.

I don't think you do. It doesn't.

However, I don't understand how it can works because

That makes sense. It can't work, because:

in my unstanding, std::variant must need the maximum size of the types it holds.


This is what the standard says:

[res.on.functions]

In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ standard library depends on components supplied by a C++ program. If these components do not meet their requirements, this document places no requirements on the implementation.

In particular, the effects are undefined in the following cases:

...

  • if an incomplete type ([basic.types]) is used as a template argument when instantiating a template component or evaluating a concept, unless specifically allowed for that component.

There is no specific rule in the section [variant] allowing incomplete types.

Upvotes: 7

Related Questions