#include <optional>
#include <variant>
#include <vector>
// A
static_assert(
std::optional<
std::vector< int >
>{ std::vector< int >{ 1, 2, 3 } }
);
// B
static_assert(
std::optional<
std::variant<
std::vector< int >
>
>{ std::vector< int >{ 1, 2, 3 } }
);
https://godbolt.org/z/jbdfPYqe1
这些示例不使用 clang (18) 进行编译。 他们确实使用 gcc/msvc 进行编译。
到底是什么导致了这种行为?有解决方法吗?
从 C++20 开始,
std::optional
的构造函数才为 constexpr
。如果将代码编译为 C++20,则 clang 编译代码不会出现错误:https://godbolt.org/z/5rnee9Yec。
如果你要求 gcc 编译为 C++17,你会得到与 clang 类似的错误:https://godbolt.org/z/GM8E843oP
事实上,gcc 和 clang 之间的行为是一致的。
我的第一个赌注是
std::optional::operator bool
,但奇怪的是,在 C++17 中已经是 constexpr
。