std::variant 和不完整类型:它是如何工作的?

Ant*_*ier 2 c++ variant

我确实明白这std::variant适用于不完整的类型。但是,我不明白它是如何工作的,因为根据我的理解,std::variant必须需要它所持有的类型的最大大小。

那么,为什么这段代码不能用s1and编译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() {}
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 5

我确实了解 std::variant 适用于不完整类型。

我不认为你这样做。事实并非如此。

但是,我不明白它是如何工作的,因为

这就说得通了。这是行不通的,因为:

根据我的理解, std::variant 必须需要它所持有的类型的最大大小。


标准是这样说的:

[功能解析]

在某些情况下(替换函数、处理函数、用于实例化标准库模板组件的类型的操作),C++ 标准库依赖于 C++ 程序提供的组件。如果这些组件不满足其要求,则本文档对实现不提出任何要求

特别是,在以下情况下效果未定义:

...

  • 如果在实例化模板组件或评估概念时使用不完整类型([basic.types])作为模板参数,除非该组件特别允许。

[variant] 部分中没有允许不完整类型的具体规则。