Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

c++ - 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() {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...