在STL容器中存储属性?
假设我有一个名为 generic_pair 的类,其形式为:
template < typename K, typename V >
struct generic_pair{
K key;
V value;
};
现在,问题是我希望能够在 STL 容器中存储一堆这些 generic_pairs 但是 并非全部 K、V>容器中的类型将相同。例如,一些元素可以是<<。 int, int >而其他人可能< int , 字符串 >等等。问题是我们怎样才能做到这一点?
我的第一个想法是使用“标签”创建封装类型的层次结构,并使用泛型类型声明容器,但使用继承类型的实际元素。例如,
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 或其他地方看到过类似的实现或相关工具/技术,那也会很有帮助。 (我试图避免宏)
Suppose I have a class called generic_pair of the form:
template < typename K, typename V >
struct generic_pair{
K key;
V value;
};
Now, the problem is I would like to be able to store a bunch of these generic_pairs in an STL container BUT not all < K, V > in the container will be of the same type. For example, some elements may be < int, int > whereas others may be < int , string > and so on. Question is how can we do this?
My first thought is to use "tags" to create a hierarchy of encapsulated types and declare the container with the generic type but actual elements with inherited types. For example,
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;
I bet there is a better, more correct way to do this? Any ideas, directions appreciated. If you have seen similar implementations or relevant tools/techniques in MPL or elsewhere that's helpful too. (I am trying to avoid macros)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果类型集,您可以使用 Boost.Variant是预先确定的。如果没有,那么 Boost.Any 可能会成功。
You can use Boost.Variant if the set of types is determined in advance. If not, then Boost.Any might do the trick.
根据您的问题和随后澄清问题的评论,以下内容将满足您的要求:
}
From your question and subsequent comments that clarify matters, the following would do what you're asking for:
}