百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

C++编程:标准库visit和variant用法

ztj100 2025-01-21 23:12 44 浏览 0 评论

类模板 std::variant 表示一个类型安全的联合体。 std::variant 的一个实例在任意时刻要么保有其一个可选类型之一的值,要么在错误情况下无值。

std::visit应用观览器 vis 到 variant 变量组 vars 。

std::visit参数:

vis

接受每个 variant 的每个可能可选项的可调用 (Callable) 对象

vars

传递给观览器的 variant 列表

例子1

  • 观察器vis针对variant每个可选项必须有之对应的函数,不能缺。
  • 返回值是观察器共同返回的类型,不能不一致。
Bash
#include <iostream>
#include <variant>

struct Apple { };
struct Orange { };
struct Banana { };
struct Pear { };

template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
template<class... Ts> overload(Ts...) -> overload<Ts...>; // C++20不在需要

int main() {
    std::variant<Apple, Orange, Banana, Pear> package =  { Banana() };

    auto result =  std::visit(overload{
        [](Apple& )      { std::cout << "Apple\n"; return 1;},
        [](Orange& )   { std::cout << "Orange\n"; return 2;},
        [](Banana& )   { std::cout << "Banana\n"; return 3;},
        [](Pear& ) { std::cout << "Pear\n"; return 4;}
    }, package);
    
    std::cout << result << std::endl;    
}

例子2

观察器的是多个variant选项笛卡尔积

Bash
#include <iostream>
#include <variant>

struct Apple { };
struct Orange { };
struct Banana { };
struct Pear { };

struct Light { };
struct Heavy { };

template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
template<class... Ts> overload(Ts...) -> overload<Ts...>; // C++20不在需要

int main() {
    std::variant<Apple, Orange> package1 =  { Orange() };
    std::variant<Light, Heavy> package2 =  { Light() };

    auto result =  std::visit(overload{
        [](Apple&, Light&)      { std::cout << "Light Apple\n"; return 1;},
        [](Orange&,  Light&)  { std::cout << "Light Orange\n"; return 2;},
        [](Apple&, Heavy&)    { std::cout << "Heavy Apple\n"; return 3;},
        [](Orange&, Heavy&) { std::cout << "Heavy Orange\n"; return 4;}
    }, package1, package2);
    
    std::cout << result << std::endl;    
}


https://wandbox.org/nojs/gcc-head
https://wandbox.org/nojs/clang-head
https://wandbox.org/permlink/wyeJ1TNulMwEM6QJ
https://wandbox.org/permlink/qpn9gVjb4vzKja0I

相关推荐

10条军规:电商API从数据泄露到高可用的全链路防护

电商API接口避坑指南:数据安全、版本兼容与成本控制的10个教训在电商行业数字化转型中,API接口已成为连接平台、商家、用户与第三方服务的核心枢纽。然而,从数据泄露到版本冲突,从成本超支到系统崩溃,A...

Python 文件处理在实际项目中的困难与应对策略

在Python项目开发,文件处理是一项基础且关键的任务。然而,在实际项目中,Python文件处理往往会面临各种各样的困难和挑战,从文件格式兼容性、编码问题,到性能瓶颈、并发访问冲突等。本文将深入...

The Future of Manufacturing with Custom CNC Parts

ThefutureofmanufacturingisincreasinglybeingshapedbytheintegrationofcustomCNC(ComputerNumericalContro...

Innovative Solutions in Custom CNC Machining

Inrecentyears,thelandscapeofcustomCNCmachininghasevolvedrapidly,drivenbyincreasingdemandsforprecisio...

C#.NET serilog 详解(c# repository)

简介Serilog是...

Custom CNC Machining for Small Batch Production

Inmodernmanufacturing,producingsmallbatchesofcustomizedpartshasbecomeanincreasinglycommondemandacros...

Custom CNC Machining for Customized Solutions

Thedemandforcustomizedsolutionsinmanufacturinghasgrownsignificantly,drivenbydiverseindustryneedsandt...

Revolutionizing Manufacturing with Custom CNC Parts

Understandinghowmanufacturingisevolving,especiallythroughtheuseofcustomCNCparts,canseemcomplex.Thisa...

Breaking Boundaries with Custom CNC Parts

BreakingboundarieswithcustomCNCpartsinvolvesexploringhowadvancedmanufacturingtechniquesaretransformi...

Custom CNC Parts for Aerospace Industry

Intherealmofaerospacemanufacturing,precisionandreliabilityareparamount.Thecomponentsthatmakeupaircra...

Cnc machining for custom parts and components

UnderstandingCNCmachiningforcustompartsandcomponentsinvolvesexploringitsprocesses,advantages,andcomm...

洞察宇宙(十八):深入理解C语言内存管理

分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“深入理解C语言内存管理”...

The Art of Crafting Custom CNC Parts

UnderstandingtheprocessofcreatingcustomCNCpartscanoftenbeconfusingforbeginnersandevensomeexperienced...

Tailored Custom CNC Solutions for Automotive

Intheautomotiveindustry,precisionandefficiencyarecrucialforproducinghigh-qualityvehiclecomponents.Ta...

关于WEB服务器(.NET)一些经验累积(一)

以前做过技术支持,把一些遇到的问题累积保存起来,现在发出了。1.问题:未能加载文件或程序集“System.EnterpriseServices.Wrapper.dll”或它的某一个依赖项。拒绝访问。解...

取消回复欢迎 发表评论: