本文介绍了如何通过decltype声明迭代器的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 98中,我通常使用以下语句在迭代器的值类型中声明变量:

In C++98, I typically use the following to declare a variable in an iterator's value type:

typename std::iterator_traits<Iterator>::value_type value;

在C ++ 11中,我们有decltype,我认为最简单的方法来推导值类型是:

In C++11 we have decltype and I had thought the easiest way to deduce the value type is:

decltype(*iterator) value;

不幸的是,对于大多数迭代器,* iterator的类型是value_type&而不是value_type。任何想法,没有类型修改类,如何按上面的产生value_type(而不是任何参考)?

Unfortunately for most iterators, the type of *iterator is value_type& and not value_type. Any ideas, without the type modification classes, how to massage the above into yielding the value_type (and not any reference)?

我不认为这个问题是不合理的,因为以下是相当健壮,但最终创建另一个变量。

I don't think the question is unreasonable given that the following is fairly robust but ends up creating another variable.

auto x = *iterator;
decltype(x) value;

还要注意,我真的想要推导类型 em> instance 如果我想声明一个std :: vector这些值。

Also note that I really want the deduced type and not just an instance e.g. if I wanted to declare a std::vector of these values.

推荐答案

继续使用 iterator_traits decltype(* iterator)甚至可以是某种奇怪的代理类,以便在表达式 * iter = something

Keep using iterator_traits. decltype(*iterator) could even be some sort of weird proxy class in order to do special things in the expression *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上的输出:

Output on MSVC 2012:

它们不一样。

这篇关于如何通过decltype声明迭代器的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 12:48