如何通过decltype声明迭代器的值

How to declare the value of an iterator through decltype

本文关键字:迭代器 声明 何通过 decltype      更新时间:2023-10-16

在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_traitsdecltype(*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");