如果我有一个类型为 std::unordered_map<aaa, bbb>
的变量,我如何访问 std::unordered_map<aaa, bbb>::iterator
typedef,而不必总是编写类型本身,但例如,让编译器从像 decltype(my_map)::iterator)
这样的现有变量推断它?
编辑:
示例代码:
#include <iostream>
#include <unordered_map>
std::unordered_map<int, int> test()
{
return std::unordered_map<int, int>();
}
int main()
{
const auto &map = test();
decltype(map)::const_iterator it;
return 0;
}
编译输出:
main.cpp: In function 'int main()':
main.cpp:13:5: error: decltype evaluates to 'const std::unordered_map&', which is not a class or enumeration type
decltype(map)::const_iterator it;
^
main.cpp:13:35: error: expected initializer before 'it'
decltype(map)::const_iterator it;
^
似乎您想从可能是引用的变量中获取迭代器类型。您可以使用std::remove_reference_t
:
#define get_iter_type(s) std::remove_reference_t<decltype(s)>::iterator
然后编译以下代码:
int main() {
std::unordered_map<int, int> mp;
const auto &s = mp;
get_iter_type(s) it;
}
多种方式:
类型别名:
using my_map_it = std::unordered_map<aaa, bbb>::iterator;
my_map_it it;
auto
推论
std::unordered_map<aaa, bbb> my_map;
auto it = my_map.begin();
decltype
std::unordered_map<aaa, bbb> my_map;
decltype(my_map.begin()) it;
decltype(my_map)::iterator it; // also valid