喜歡這篇文章嗎?喜歡的話去看博主的置頂博客,即可依據分類找到此文章的原版得到更好的體驗,
圖片及代碼顯示的問題,筆者深感抱歉,想要更好的體驗去原博文即可。
title: ‘Boost學習筆記4 - Boost::Variant’
mathjax: true
date: 2020-03-17 19:29:36
categories: [c++筆記,Boost學習筆記]
tags: [c++筆記,Boost學習筆記]
keywords: [c++筆記,Boost學習筆記]
Boost::Variant
boost::variant和any很像,variant和any一樣在C++17中被編入STL
variant可以指定一部分數據類型,你可以在這一部分中隨便賦值,就像下面寫到的一樣,另外和any的any_cast不一樣的是variant使用get<T>來獲得內容。
#include <boost/variant.hpp>
#include <iostream>
#include <string>
int main() {
boost::variant<double, char, std::string> v;
v = 3.14;
std::cout << boost::get<double>(v) << std::endl;
v = 'A';
// std::cout << boost::get<double>(v) << std::endl; 這句現在會報錯
std::cout << boost::get<char>(v) << std::endl;
v = "Hello, world!";
std::cout << boost::get<std::string>(v) << std::endl;
}
訪問者模式
variant允許我們使用訪問者模式來訪問其內部的成員,使用函數boost::apply_visitor來實現,訪問者模式使用的時候重載仿函數。仿函數記得繼承static_visitor即可。
#include <boost/variant.hpp>
#include <iostream>
#include <string>
struct visit : public boost::static_visitor<> {
void operator()(double &d) const { std::cout << "double" << std::endl; }
void operator()(char &c) const { std::cout << "char" << std::endl; }
void operator()(std::string &s) const { std::cout << "string" << std::endl; }
};
int main() {
boost::variant<double, char, std::string> v;
v = 3.14;
boost::apply_visitor(visit(), v);
v = 'A';
boost::apply_visitor(visit(), v);
v = "Hello, world!";
boost::apply_visitor(visit(), v);
}
輸出
double
char
string