gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:13:26 27 4
gpt4 key购买 nike

在 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>>>

它们不一样。

关于c++ - 如何通过 decltype 声明迭代器的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15560912/

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