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

风流意气都作罢 提交于 2020-01-16 09:09:14

问题


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() {}

回答1:


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.



来源:https://stackoverflow.com/questions/57226629/stdvariant-and-incomplete-type-how-does-it-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!