std::visit
性病:访问
Defined in header | | |
---|---|---|
template <class Visitor, class... Variants> constexpr /*see below*/ visit(Visitor&& vis, Variants&&... vars | | (since C++17) |
应用访客vis
变式vars
...
有效地返回。
std::invoke(std::forward<Visitor>(vis), std::get<is>(std::forward<Variants>(vars))...)...
,在哪里is...
是vars.index()...
...
如果上面的调用不是相同类型和值类别的有效表达式,则调用是格式错误的,对于所有变体的所有可选类型的组合都是如此。
参数
vis | - | a Callable that accepts every possible alternative from every variant |
---|---|---|
vars | - | list of variants to pass to the visitor |
返回值
选定的访问者调用返回的值,转换为所有可能的公共类型。std::invoke
表情。
例外
抛出std::bad_variant_access
如果在vars
是valueless_by_exception
...
复杂性
当变量数为0或1时,可调用对象的调用将在固定时间内实现,即不依赖于sizeof...(Types)
...
如果变体数大于1,则调用可调用对象没有复杂要求。
例
二次
#include <variant>
#include <iostream>
#include <type_traits>
#include <iomanip>
#include <vector>
template<class T> struct always_false : std::false_type {};
using var_t = std::variant<int, long, double, std::string>;
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main() {
std::vector<var_t> vec = {10, 15l, 1.5, "hello"};
for(auto& v: vec) {
// void visitor, only called for side-effects
std::visit([](auto&& arg){std::cout << arg;}, v
// value-returning visitor. A common idiom is to return another variant
var_t w = std::visit([](auto&& arg) -> var_t {return arg + arg;}, v
std::cout << ". After doubling, variant holds ";
// type-matching visitor: can also be a class with 4 overloaded operator()'s
std::visit([](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, int>)
std::cout << "int with value " << arg << '\n';
else if constexpr (std::is_same_v<T, long>)
std::cout << "long with value " << arg << '\n';
else if constexpr (std::is_same_v<T, double>)
std::cout << "double with value " << arg << '\n';
else if constexpr (std::is_same_v<T, std::string>)
std::cout << "std::string with value " << std::quoted(arg) << '\n';
else
static_assert(always_false<T>::value, "non-exhaustive visitor!"
}, w
}
for (auto& v: vec) {
std::visit(overloaded {
[](int arg) { std::cout << arg << ' '; },
[](long arg) { std::cout << arg << ' '; },
[](double arg) { std::cout << arg << ' '; },
[](const std::string& arg) { std::cout << std::quoted(arg) << ' '; },
}, v
}
}
二次
产出:
二次
10. After doubling, variant holds int with value 20
15. After doubling, variant holds long with value 30
1.5. After doubling, variant holds double with value 3
hello. After doubling, variant holds std::string with value "hellohello"
10 15 1.5 "hello"
二次
另见
swap | swaps with another variant (public member function) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。