如何优雅地获取返回值 ranged-base 循环的类型?
我目前使用这个:-(它工作正常)
using Encapsulator= std::vector<int>; //<-- any datastructure
using ReturnType = decltype(std::declval<Encapsulator>().begin().operator*());
//^ ReturnType is "int&"
目标:ReturnType
是一种符合单词auto
的类型:-
for(auto returnType : an-instance-of-Encapsulator ){}
但是,我觉得我上面的代码一点都不优雅。
看久了觉得头晕。
问题
标准库/语法中有没有像这样优雅地工作的东西?
using ReturnType = std::rangedBasedLoopType<Encapsulator>;
我想知道我是否应该自己编写 rangedBasedLoopType
代码,但我正在努力避免重新发明轮子。
我重新发明轮子
我的坏...我无法抗拒。此代码工作正常。
template<class Collection> using GetReturn =
decltype(std::declval<Collection>().begin().operator*());
using ReturnType = GetReturn<Encapsulator>;
编辑(接受答案后):
对我来说,这两个答案都很好。非常感谢!
R Sahu 很整洁,而干杯和hth。 - Alf 的更健壮。
很遗憾我只能接受一个,所以我选择了适合我的小项目的那个。
最佳答案
最直接的方法:
using Encapsulator= std::vector<int>;
using ItemType = Encapsulator::value_type; //
using ValueType = Encapsulator::value_type; // Use on of these three
using ReturnType = Encapsulator::value_type; //
所有标准库容器都支持value_type
。参见 http://en.cppreference.com/w/cpp/concept/Container .
关于c++ - **直接**获取基于范围的循环中的元素类型,例如对于 "using",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42337435/