This question already has answers here:
Where and why do I have to put the “template” and “typename” keywords?
                                
                                    (6个答案)
                                
                        
                                2年前关闭。
            
                    
下一段代码编译成功:

#include <map>

template<typename KEY>
using umap = std::map<KEY, std::wstring>;

int main()
{
  umap<int> m;
  umap<double> m2;
}


同时,以与映射相同的方式添加迭代器模板会使编译器发誓并抱怨错误C2061:语法错误。因此,下一个块将不会编译:

template<typename KEY>
using umap = std::map<KEY, std::wstring>;

template<typename KEY>
using iter = std::map<KEY, std::wstring>::iterator;

int main()
{
  umap<int> m;
  umap<double> m2;
}


我们不能在迭代器中使用别名声明吗?为什么?会解决吗?

最佳答案

您需要在typename之前使用std::map<KEY, std::wstring>::iterator关键字,因为它是一个依赖范围。

因此,您的第二个代码应为:

template<typename KEY>
using umap = std::map<KEY, std::wstring>;

template<typename KEY>
using iter = typename std::map<KEY, std::wstring>::iterator;

int main()
{
  umap<int> m;
  umap<double> m2;
}

关于c++ - Visual Studio上带有容器迭代器的Alias模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42952820/

10-15 06:02