C++ (Qt)variant<int, double, std::string> v = 10; if (v.is_type<int>()) std::cout << v.get<int>() << std::endl; v = 0.5;std::cout << v.get<double>() << std::endl; v = std::string("hello-hello");std::cout << v.get<std::string>() << std::endl;
C++ (Qt)#include <iostream>#include <list>#include <variant.h> typedef variant<int, double, std::string> my_variant; void print_int(const my_variant & v){ std::cout << " int " << v.get<int>() << std::endl;} void print_double(const my_variant & v){ std::cout << " double " << v.get<double>() << std::endl;} void print_str(const my_variant & v){ std::cout << " str " << v.get<std::string>() << std::endl;} int main(){ std::list<my_variant> list; list.push_back(10); list.push_back(0.5); list.push_back(std::string("hello-hello")); variant_visitor<int, double, std::string> my_visitor; my_visitor.reg<int>(&print_int); my_visitor.reg<double>(&print_double); my_visitor.reg<std::string>(&print_str); for (auto v : list) my_visitor(v); return 0;}
Bashint 10double 0.5str hello-hello
C++ (Qt) my_visitor.reg<int>(&print_int); my_visitor.reg<double>(&print_double); my_visitor.reg<std::string>(&print_str);
C++ (Qt)#include <iostream>#include <list>#include <variant.h>#include <string> typedef variant<int, double, std::string> variant_t; int main(){ std::list<variant_t> list; list.push_back(std::string("-42.45938")); // string list.push_back(0.5); // double list.push_back(std::string("2.34")); // string list.push_back(3.565); // double list.push_back(10); // int variant_visitor<double (variant_t)> my_visitor; my_visitor.reg<int>([](variant_t v) { return v.get<int>(); } ); my_visitor.reg<double>([](variant_t v) { return v.get<double>(); } ); my_visitor.reg<std::string>([](variant_t v) { return std::stod(v.get<std::string>()); } ); for (auto v : list) std::cout << my_visitor(v) << std::endl; list.sort([&](variant_t v1, variant_t v2) { return my_visitor(v1) > my_visitor(v2); }); std::cout << "--------------------------------" << std::endl; for (auto v : list) std::cout << my_visitor(v) << std::endl; return 0;}
C++ (Qt)bool IsLess( const Variant & v1, const Variant & v2 ){ double d1, d2; bool num1 = TryConvert2Double(v1, &d1); bool num2 = TryConvert2Double(v2, &d2); if (num1 && num2) return d1 < d2; return num1 && !num2;}