如何通过decltype声明迭代器的值
How to declare the value of an iterator through decltype
在c++ 98中,我通常使用以下语句来声明迭代器值类型的变量:
typename std::iterator_traits<Iterator>::value_type value;
在c++ 11中,我们有decltype,我认为推断值类型最简单的方法是:
decltype(*iterator) value;
不幸的是,对于大多数迭代器来说,*迭代器的类型是value_type&而不是value_type。在没有类型修改类的情况下,有什么想法吗?如何将上面的内容转换为value_type(而不是任何引用)?
我不认为这个问题是不合理的,因为下面的代码相当健壮,但最终会创建另一个变量。
auto x = *iterator;
decltype(x) value;
还要注意,我真正想要的是推导出来的类型,而不仅仅是一个实例,例如,如果我想声明这些值的std::vector
继续使用iterator_traits
。decltype(*iterator)
甚至可以是某种奇怪的代理类,以便在表达式*iter = something
中做特殊的事情。
的例子:
#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>>>
它们不一样
对于这个用例,我喜欢std::decay。通常我会使用
std::vector< int > vec;
using value_type = typename std::decay< decltype(*begin(vec)) >::type;
static_assert(std::is_same< int, value_type >::value, "expected int");
相关文章:
- 为什么此函数返回一个link_type但它被声明为迭代器
- 在 leveldb 的 c++ 示例中声明迭代器时出现分段错误
- 如何修复错误,迭代器未在此范围内声明,并且迭代器未命名类型'
- 如何将迭代器变量声明为私有成员变量
- 什么时候足以将const_iterator声明为const迭代器
- 声明一个模板函数,该函数接收两个泛型迭代器作为参数
- C 迭代器从Typedef std :: Map作为模板参数声明
- 在 GCC 上自动声明映射迭代器错误
- ISO C++禁止声明没有自动迭代器类型的“it”
- 声明泛型迭代器
- 迭代器的声明:"does not contain a type"
- 如何在 C++ 中为堆栈集声明迭代器
- 如何正确地声明从非常量迭代器到指针的常量指针
- 模板化的迭代器声明
- 如何向派生类对象声明迭代器
- 如何在for循环中声明第二个迭代器
- 如何为未知容器声明迭代器变量
- std::list< pair<double, int> >::迭代器声明不起作用
- 这个迭代器声明有什么问题
- 语义迭代器声明