本文主要是介绍C++ variant (tcy),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.1.用途:用于存储和操作不同类型对象,是一个类型安全的联合体(union).variant实例存储某一类型的数据,可指定重复的数据类型.
1.2.注意:variant的指定类型不能是引用类型,数组类型以及void类型,
1.3.说明:默认以首个指定类型进行初始化,首个类型必须支持默认构造函数
1.4.variant<> 操作constructors //构造函数-创建variant对象(调用底层类型构造函数)= //分配新值emplace<K|Idx>() //为类型T|索引Idx备选项分配一新值bool valueless_by_exception()//判断该变量是否由于异常而没有值size_t index() //返回当前备选项索引swap() //交换两个对象的值==, !=, <, <=, >, >= //比较variant对象hash<> //计算哈希值holds_alternative<K>() //检查变量当前是否具有给定类型-类型T是否有值get<K|Idx>() //获取类型K|索引Idx的值(如无值抛异常)get_if<K|Idx>() //获取类型K|索引Idx的值的指针(如无值抛异常)visit() //为当前备选项执行仿函数的操作
2.实例: 基本测试
示例1:#include <iostream> #include <string> #include<variant>#include<vector>#include<cassert> #include<cmath>using namespace std; void test_base() {// 定义支持int、float、string的类型std::variant<int, float, std::string> x;//获取修改值:x = 1; assert(std::get<int>(x) == 1 && std::get<0>(x) == 1);x = 3.14f; assert(std::get<float>(x) == 3.14f && std::get<1>(x) == 3.14f);x = "Tom"; assert(std::get<string>(x) == string("Tom"));x.emplace<string>("Bob"); assert(std::get<2>(x) == string("Bob"));//获取变量的指针:x = 10; auto px = std::get_if<int>(&x); cout << *px << endl;//10//获取变量索引:x = 1; assert(x.index() == 0);x = 3.14f; assert(x.index() == 1);x = "Tom"; assert(x.index() == 2);//判断变量是否有值:cout << holds_alternative<string>(x) << endl;//true 有字符串值cout << holds_alternative<int>(x) << endl; //false 无int值}
测试无效值:
void test_error(){//变量无效:struct A {A(int) {};A& operator= (const A&) = default;A(const A&) { throw std::domain_error("copy ctor"); } };std::variant<std::string, A> var{ "str" };assert(var.valueless_by_exception() == false);try {var = A{ 6 };}catch (const std::domain_error& ex) {std::cout << "1) Exception: " << ex.what() << '\n';}assert(var.index() == std::variant_npos);assert(var.valueless_by_exception() == true);//由var初始化过程抛出异常造成var是“无效值” try {std::get<1>(var);}catch (const std::bad_variant_access& ex) {std::cout << "2) Exception: " << ex.what() << '\n';}var = "str2";assert(var.index() == 0);assert(std::get<0>(var) == "str2");assert(var.valueless_by_exception() == false);/*//输出:1) Exception: copy ctor2) Exception: bad variant access*/}
应用场景1、函数返回不同类型的返回值
//使用 visit 的方式访问struct DataIncVisitor {void operator() (int &i) const { i += 1; }void operator() (float &f) const { f += 1.0f; }void operator() (std::string &s) const { s += "!"; }};//应用场景1、函数返回不同类型的返回值//ax^2+bx+c=0求根,根可能是一个,两个,无根using Two = std::pair<double, double>;using Roots = std::variant<Two, double, void*>;Roots getRoots(double a, double b, double c){auto d = b * b - 4 * a*c;if (d > 0.0){auto p = sqrt(d);return std::make_pair((-b + p) / 2 * a, (-b - p) / 2 * a);}else if (d == 0.0)return (-1 * b) / (2 * a);return nullptr;}struct printRootVistor{void operator()(const Two& roots) const{cout << "two roots: " << roots.first << "," << roots.second << '\n';}void operator()(double root) const{cout << "one root: " << root << '\n';}void operator()(void *) const{cout << "No real roots found.\n";}};
应用场景2、多态
struct Triangle { void Draw() const { cout << "△" << endl; } };struct Circle { void Draw() const { cout << "○" << endl; } };void test_visit() {std::variant<int, float, std::string> i=2,f=3.14f,s="Tom";//加1测试:std::visit(DataIncVisitor(), i); assert(std::get<int>(i) == 3);std::visit(DataIncVisitor(), f); cout << std::get<float>(f) << endl;//4.14有误差 std::visit(DataIncVisitor(), s);assert(std::get<string>(s) == string("Tom!"));//求根:std::visit(printRootVistor(), getRoots(1, -2, 1)); //(x-1)*(x-1)=0std::visit(printRootVistor(), getRoots(1, -3, 2)); //(x-2)*(x-1)=0std::visit(printRootVistor(), getRoots(1, 0, 2)); //x*x - 2 = 0//多态测试:using Draw = std::variant<Triangle, Circle>;Draw draw;std::vector<Draw> draw_list{ Triangle{}, Circle{}};auto DrawVisitor = [](const auto &t) { t.Draw(); };for (const auto &item : draw_list) {std::visit(DrawVisitor, item);}}int main() {test_base();test_error();test_visit(); }
实例3:
#include <variant>template <size_t n, typename... Args>std::variant<Args...> _tuple_index(size_t i, const std::tuple<Args...>& tpl) {if (i == n)return std::get<n>(tpl);else if (n == sizeof...(Args) - 1)throw std::out_of_range("越界.");elsereturn _tuple_index<(n < sizeof...(Args)-1 ? n+1 : 0)>(i, tpl);}template <typename... Args>std::variant<Args...> tuple_index(size_t i, const std::tuple<Args...>& tpl) {return _tuple_index<0>(i, tpl);}
这篇关于C++ variant (tcy)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!