gpt4 book ai didi

c++ - 是否可以从任意迭代器(C++)中获取值类型?

转载 作者:IT老高 更新时间:2023-10-28 22:37:01 28 4
gpt4 key购买 nike

我有课

template <typename Iterator, typename Value>
class Foo {
public:
Foo(const Iterator& it) { ... }
...
private:
map<Value, int> m_;
}
};

有什么办法可以去掉模板中的 Value 吗? Iterator 可能是也可能不是 STL 迭代器,但保证 *it 类型是 Value。

我知道 iterator_traits<T>::value_type对于 STL 迭代器,但想知道是否有任何方法可以为任意迭代器类型自动获取值类型?

我正在考虑的一个技巧 - 比如说,我们有一个辅助类

template <typename Iterator, typename Value>
class Bar {
public:
Bar(const Iterator& dummy_iterator, const Value& dummmy_value) {}
...
};

那么如果我们将 Bar 实例化为 Bar(it, *it),那么在 Bar 内部就会知道 Value 的类型。但是我找不到将 Bar 与 Foo 结合起来的好方法。

最佳答案

任何迭代器都应该提供iterator_traits<Iterator>::value_type .如果不是,那么它不是迭代器。 ISO C++ 2003 24.3.1[lib.iterator.traits]“迭代器特征”:

To implement algorithms only in terms of iterators, it is often necessary to determine the value and difference types that correspond to a particular iterator type. Accordingly, it is required that if Iterator is the type of an iterator, the types

iterator_traits<Iterator>::difference_type
iterator_traits<Iterator>::value_type
iterator_traits<Iterator>::iterator_category

be defined as the iterator’s difference type, value type and iterator category, respectively.

除此之外,没有通用的方法来获取任意 C++ 表达式的类型。 C++0x 将通过提供 decltype 来纠正它.

关于c++ - 是否可以从任意迭代器(C++)中获取值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1107149/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com