考虑以下:
struct foo {
};
struct bar {
};
int main()
{
foo f;
bar b;
std::variant<foo*, bool> v;
v = &b; // compiles in Visual Studio 19 v16.7.3
}
正如评论中所讨论的,我相信以上是合法的 C++17。有一个提案P0608R3被接受为解决这种令人惊讶的行为的标准,但它在 2018 年(在圣地亚哥会议上)被接受,因此适用于 C++20 而不是 C++17。此外,P0608R3 当前未在 Visual Studio 中实现,即使编译为 C++20 预览版也是如此。
从指向非 foo 的指针创建此变体的最佳/最简洁的方法是编译时错误?我相信以下内容有效,但如果变体包含多个项目,则有很多样板。
struct foo {
};
struct bar {
};
using variant_type = std::variant<foo*, bool>;
struct var_wrapper : public variant_type
{
var_wrapper(foo* v = nullptr) : variant_type(v)
{}
var_wrapper(bool v) : variant_type(v)
{}
template<typename T>
var_wrapper(T*) = delete;
};
int main()
{
foo f;
bar b;
var_wrapper vw;
vw = &f; // fine
vw = true; // fine
vw = &b; // compile time error
}
我错过了一些更简单的方法吗?