0

假设我有一个名为 generic_pair 的类,其形式为:

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

现在,问题是我希望能够将一堆这些 generic_pairs 存储在 STL 容器中,容器中的所有 <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 或其他地方看到过类似的实现或相关工具/技术,那也很有帮助。(我试图避免宏)

4

2 回答 2

3

根据您的问题和随后澄清问题的评论,以下内容将满足您的要求:

#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;
}

}

于 2010-11-02T23:54:51.467 回答
3

如果预先确定了类型集,则可以使用Boost.Variant 。如果没有,那么Boost.Any可能会成功。

于 2010-11-02T23:34:17.317 回答