本文整理汇总了C++中variant::index方法的典型用法代码示例。如果您正苦于以下问题:C++ variant::index方法的具体用法?C++ variant::index怎么用?C++ variant::index使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类variant
的用法示例。
在下文中一共展示了variant::index方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main()
{
using namespace ranges;
// Simple variant and access.
{
variant<int, short> v;
CHECK(v.index() == 0u);
auto v2 = v;
CHECK(v2.index() == 0u);
v.emplace<1>((short)2);
CHECK(v.index() == 1u);
CHECK(get<1>(v) == (short)2);
try
{
get<0>(v);
CHECK(false);
}
catch(bad_variant_access)
{}
catch(...)
{
CHECK(!(bool)"unknown exception");
}
v = v2;
CHECK(v.index() == 0u);
}
// variant of void
{
variant<void, void> v;
CHECK(v.index() == 0u);
v.emplace<0>();
CHECK(v.index() == 0u);
try
{
// Will only compile if get returns void
v.index() == 0 ? void() : get<0>(v);
}
catch(...)
{
CHECK(false);
}
v.emplace<1>();
CHECK(v.index() == 1u);
try
{
get<0>(v);
CHECK(false);
}
catch(bad_variant_access)
{}
catch(...)
{
CHECK(!(bool)"unknown exception");
}
}
// variant of references
{
int i = 42;
std::string s = "hello world";
variant<int&, std::string&> v{emplaced_index<0>, i};
CONCEPT_ASSERT(!DefaultConstructible<variant<int&, std::string&>>());
CHECK(v.index() == 0u);
CHECK(get<0>(v) == 42);
CHECK(&get<0>(v) == &i);
auto const & cv = v;
get<0>(cv) = 24;
CHECK(i == 24);
v.emplace<1>(s);
CHECK(v.index() == 1u);
CHECK(get<1>(v) == "hello world");
CHECK(&get<1>(v) == &s);
get<1>(cv) = "goodbye";
CHECK(s == "goodbye");
}
// Move test 1
{
variant<int, MoveOnlyString> v{emplaced_index<1>, "hello world"};
CHECK(get<1>(v) == "hello world");
MoveOnlyString s = get<1>(std::move(v));
CHECK(s == "hello world");
CHECK(get<1>(v) == "");
v.emplace<1>("goodbye");
CHECK(get<1>(v) == "goodbye");
auto v2 = std::move(v);
CHECK(get<1>(v2) == "goodbye");
CHECK(get<1>(v) == "");
v = std::move(v2);
CHECK(get<1>(v) == "goodbye");
CHECK(get<1>(v2) == "");
}
// Move test 2
{
MoveOnlyString s = "hello world";
variant<MoveOnlyString&> v{emplaced_index<0>, s};
CHECK(get<0>(v) == "hello world");
//.........这里部分代码省略.........
示例2: bool
explicit operator bool() const noexcept
{
return data_.index() != 0;
}