在 C++98 中,我通常使用以下代码来声明迭代器值类型中的变量:
typename std::iterator_traits<Iterator>::value_type value;
在 C++11 中,我们有 decltype,我认为推断值类型的最简单方法是:
decltype(*iterator) value;
不幸的是,对于大多数迭代器来说,*iterator 的类型是 value_type& 而不是 value_type。有什么想法,在没有类型修改类的情况下,如何将上述内容转化为产生 value_type (而不是任何引用)?
我不认为这个问题是不合理的,因为以下内容相当强大,但最终创建了另一个变量。
auto x = *iterator;
decltype(x) value;
另请注意,我真的想要推导类型而不仅仅是一个instance例如如果我想声明这些值的 std::vector 。
继续使用iterator_traits
. decltype(*iterator)
甚至可能是某种奇怪的代理类,以便在表达式中执行特殊操作*iter = something
.
Example:
#include <iostream>
#include <iterator>
#include <typeinfo>
#include <vector>
template <typename T>
void print_type()
{
std::cout << typeid(T).name() << std::endl;
}
template <typename Iterator>
void test(Iterator iter)
{
typedef typename
std::iterator_traits<Iterator>::value_type iter_traits_value;
auto x = *iter;
typedef decltype(x) custom_value;
print_type<iter_traits_value>();
print_type<custom_value>();
}
int main()
{
std::vector<int> a;
std::vector<bool> b;
test(a.begin());
test(b.begin());
}
MSVC 2012 的输出:
int
int
bool
class std::_Vb_reference<struct std::_Wrap_alloc<class std::allocator<unsigned int>>>
他们不一样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)