Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

variant

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() {}
like image 596
Antoine Morrier Avatar asked Jun 02 '26 02:06

Antoine Morrier


1 Answers

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.

like image 173
eerorika Avatar answered Jun 04 '26 22:06

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!