std::variant 和不完整的类型:它是如何工作的?
std::variant and incomplete type: how does it work?
我确实知道 std::variant
适用于不完整的类型。但是,我不明白它是如何工作的,因为根据我的理解,std::variant
必须需要它所拥有的类型的最大大小。
那么,为什么这段代码不能用 s1
和 s2
编译。如何让它像 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() {}
I do understand that std::variant works with incomplete type.
我不认为你知道。它没有。
However, I don't understand how it can works because
有道理。它不能工作,因为:
in my unstanding, std::variant must need the maximum size of the types it holds.
标准是这样说的:
[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.
[variant] 部分没有特定规则允许不完整的类型。
我确实知道 std::variant
适用于不完整的类型。但是,我不明白它是如何工作的,因为根据我的理解,std::variant
必须需要它所拥有的类型的最大大小。
那么,为什么这段代码不能用 s1
和 s2
编译。如何让它像 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() {}
I do understand that std::variant works with incomplete type.
我不认为你知道。它没有。
However, I don't understand how it can works because
有道理。它不能工作,因为:
in my unstanding, std::variant must need the maximum size of the types it holds.
标准是这样说的:
[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.
[variant] 部分没有特定规则允许不完整的类型。