簡體   English   中英

在STL容器中存儲屬性?

[英]Storing attributes in a STL container?

假設我有一個名為generic_pair的類,其形式為:

template < typename K, typename V >
struct generic_pair{
  K key;
  V value;
};

現在,問題是我希望能夠在STL容器中存儲一堆這些generic_pair, 並非容器中的所有<K,V>都是同一類型。 例如,某些元素可能是<int,int>,而另一些元素可能是<int,string>,依此類推。 問題是我們該怎么做?

我的第一個想法是使用“標簽”創建封裝類型的層次結構,並使用通用類型聲明容器,而使用繼承類型聲明實際元素。 例如,

struct base_type{
  typedef void type;
};

struct int_type: base_type{
  typedef int type;
}

struct string_type: base_type{
  typedef std::string type;
}

/// and so on establish a type hierarchy as necessary and then...

std::vector < generic_pair < base_type, base_type > > vec;

我敢打賭,有更好,更正確的方法嗎? 任何想法,方向表示贊賞。 如果您在MPL或其他地方看到過類似的實現或相關的工具/技術,那也很有幫助。 (我試圖避免宏)

如果類型集是預先確定的,則可以使用Boost.Variant 如果沒有,那么Boost.Any可能會成功。

根據您的問題以及隨后的澄清事項,以下內容將滿足您的要求:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

// All class-template instantiations derive from this
struct AbstractPair
{
    virtual std::string serialize() const = 0;
};

template<typename K, typename V>
struct Pair : public AbstractPair
{
public:
    Pair(K key, V value) : key(key), value(value) {}

    std::string serialize() const
    {
        std::stringstream ss;
        ss << "Key: " << key << ", Value: " << value;
        return ss.str();
    }
    K key;
    V value;
};


int main()
{
    // Vector of pointers-to-abstract-base
    std::vector<AbstractPair *> v;

    // Create derived objects (instantiate class template)
    AbstractPair *p1 = new Pair<int,int>(5,10);
    AbstractPair *p2 = new Pair<float,std::string>(3.2f, "Hello");

    // Valid, and type-safe
    v.push_back(p1);
    v.push_back(p2);

    // Demonstrate polymorphism
    for(std::vector<AbstractPair *>::iterator it = v.begin(); it != v.end(); ++it)
    {
        std::cout << (*it)->serialize() << std::endl;
    }

    // Boilerplate cleanup
    delete p1;
    delete p2;
    return 0;
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM