C++的 value_type 可以从 iterator_traits 扩展到所有类型吗?
我想创建一个类似于 std::iterator_traits::value_type 的构造,它可以使用相同的语法无缝地用于所有类型。假设我们有以下内容:
template <typename T>
struct value_type {
typedef T type;
};
#define VALUE_TYPE(T) typename value_type<T >::type
这适用于 POD 类型。我可以将它专门用于我自己的类:
struct MyClass {
typedef float value_type;
};
template <>
struct value_type<MyClass> {
typedef MyClass::value_type type;
};
尽管我更愿意在理想的世界中避免额外的 value_type 实例化。
问题出在 STL 迭代器上。我需要一种专业化来帮助我了解迭代器层次结构。这会失败,因为编译器选择基本情况:
template <>
struct value_type<std::_Iterator_base_aux> { // MSVC implementation
typedef value_type type;
};
选择层次结构较高的类(_Iterator_with_base 是最自然的,因为那是定义 value_type 的地方)失败,因为它需要将所有迭代器特征指定为模板参数。
我想要做的事情在 C++ 中是否可行?
I would like to create a construct similar to std::iterator_traits::value_type that can work seamlessly for all types using the same syntax. Imagine we have the following:
template <typename T>
struct value_type {
typedef T type;
};
#define VALUE_TYPE(T) typename value_type<T >::type
This will work for POD types. I can specialize it for my own class:
struct MyClass {
typedef float value_type;
};
template <>
struct value_type<MyClass> {
typedef MyClass::value_type type;
};
though I would prefer to avoid extra value_type instantiations in an ideal world.
The problem is with STL iterators. I need a specialization that gets me to the iterator hierarchy. This fails because the compiler chooses the base case:
template <>
struct value_type<std::_Iterator_base_aux> { // MSVC implementation
typedef value_type type;
};
Choosing a class higher up the hierarchy (_Iterator_with_base would be most natural because that is where value_type is defined) fails because it requires specifying all the iterator traits as template arguments.
Is what I'm trying to do even possible in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 SFINAE 来检测
value_type
typedef 是否存在。无需专门针对单个类型(这可能是不可能的,因为您完全依赖于内部实现细节)。You can use SFINAE to detect the presence of the
value_type
typedef. No need to specialize for individual types (which might not be possible, since you'd be relying entirely on internal implementation details).UncleBens
已经使用了SFINAE,但实际上还有更简单的:现在,如果你想将它与你控制的类一起使用,最简单的方法是:
如果你想将它用于你不控制的类,您仍然有专门化:
如果您尝试对没有内部
typedef
且没有可用专门化的类使用value_type
,则会出现编译错误(并且乍一看你不太可能理解的消息......)UncleBens
has used SFINAE, but there is actually simpler:Now, if you want to use it with a class you control, the easiest way is:
And if you want to use for a class you do not control, you still have specialization:
If you try to use
value_type
for a class that does not have an innertypedef
and for which no specialization is available, it's a compilation error (and a message you are not likely to understand at first glance...)