boost::variant的簡單介紹

boost::variant簡介
boost::Variant 是定義在boost/variant.hpp中的模板類,它的功能類似與union。Variant是一個模板,所以在使用時必須傳入至少一個類型參數。Variant實例所存儲的數據類型只能是傳入類型中的一種。
例如:

boost::Variant<double, int, string> variant;
variant = "hello world!";
variant = 3.14;
variant = 356;

boost::apply_visitor()與boost::static_visitor

boost::apply_visitor()是boost中提供的函數,該函數的第一個參數必須是boost::static_visitor類型的子類,第二個參數是boost::Variant類型。boost::static_visitor的子類中必須提供operator()()的重載,分別用於處理boost::Variant中傳入的不同類型的參數。在使用時boost::apply_visitor會自動根據第二個參數類型來調用operator()()。
例如:
源碼實例:

#include <iostream>
#include <boost/variant.hpp>
#include <string>

using namespace std;

struct Var: public boost::static_visitor<>
{
    void operator()(const double &t) 
    {
        cout << "The type is double, the value is: " << t << endl;
    }
    void operator()(const int &t) 
    {
        cout << "The type is int, the value is: " << t << endl;
    }
    void operator()(const string &t)
    {
        cout << "The type is string, the value is: " << t << endl;
    }
};


int main(int argc, char* argv[])
{
    Var v;
    boost::variant<double, int, string> var;
    var = 356;
    boost::apply_visitor(v, var);
    var = 3.14;
    boost::apply_visitor(v, var);
    var = "hello world";
    boost::apply_visitor(v, var);

    return 0;
}

運行結果:

The type is int, the value is: 356
The type is double, the value is: 3.14
The type is string, the value is: hello world
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章