c++ - 模板 std::map::iterator 实例化

标签 c++ templates dictionary iterator

<分区>

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?
map iterator in template function unrecognized by compiler

我有一个模板函数,其中有 std::map::iterator 实例化 -

template <class B , class C> 
C getValue (B& myMap , C returnType) {
    map<string,C>::iterator it = myMap.find(var);
    // implementation ...
}

并提示错误——

In function ‘C getValue(char*, B&, C)’:
error: expected ‘;’ before ‘it’
error: ‘it’ was not declared in this scope

我应该如何正确制作它?

最佳答案

它是一个依赖类型,所以你需要typename:

typename map<string,C>::iterator it = myMap.find(var);

参见 Where and why do I have to put the "template" and "typename" keywords? 更多详细信息。

正如 Zoidberg' 评论的那样, C++11 有 auto 指示编译器推导类型。参见 Elements of Modern C++ Style简要概述(以及一些其他功能)。

关于c++ - 模板 std::map::iterator 实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13743563/

相关文章:

c# - 有没有更好的方法来用通用数学实例化常量?

c++ - "generalized"有限状态机实现

c++ - 用于测试 func(args) 是否格式正确且具有必需的返回类型的特征

python - 如何从字典中获取排名列表?

python - 如何仅更改 numpy 数组字典中的一个值

c# - 将非 C++ 子项目集成到 CMake 项目中

c# - 从 C# 调用非托管 dll。拍2张

c++ - 如何为大型网格实现 VBO 并获得流畅的动画?

c++ - 如何修复: Executing lambda expression using pthread in c++

python - 如何根据值合并两个字典列表