Gle*_*Low 8 c++ iterator decltype type-traits c++11
在C++ 98中,我通常使用以下命令在迭代器的值类型中声明一个变量:
typename std::iterator_traits<Iterator>::value_type value;
Run Code Online (Sandbox Code Playgroud)
在C++ 11中我们有decltype并且我认为推导值类型的最简单方法是:
decltype(*iterator) value;
Run Code Online (Sandbox Code Playgroud)
不幸的是,对于大多数迭代器,*iterator的类型是value_type&而不是value_type.任何想法,没有类型修改类,如何按摩上面产生value_type(而不是任何参考)?
我不认为这个问题是不合理的,因为以下内容相当稳健但最终会创建另一个变量.
auto x = *iterator;
decltype(x) value;
Run Code Online (Sandbox Code Playgroud)
另请注意,我真的想要推导出的类型,而不仅仅是一个实例,例如,如果我想声明这些值的std :: vector.
asc*_*ler 17
继续使用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());
}
Run Code Online (Sandbox Code Playgroud)
MSVC 2012上的输出:
int
int
bool
class std::_Vb_reference<struct std::_Wrap_alloc<class std::allocator<unsigned int>>>
他们不一样.
| 归档时间: |
|
| 查看次数: |
3188 次 |
| 最近记录: |