C++ 在MSVC和g+中使用模板的差异+;
在将代码从Windows移植到Linux时,模板遇到了奇怪的问题 所提供的示例使用MSVC编译,工作完美 代码示例:C++ 在MSVC和g+中使用模板的差异+;,c++,visual-c++,g++,C++,Visual C++,G++,在将代码从Windows移植到Linux时,模板遇到了奇怪的问题 所提供的示例使用MSVC编译,工作完美 代码示例: #include <vector> #include <iostream> typedef std::vector<int> IntArray; template <typename TArray> void printArray(TArray a) { typedef TArray::iterator iter;
#include <vector>
#include <iostream>
typedef std::vector<int> IntArray;
template <typename TArray>
void printArray(TArray a)
{
typedef TArray::iterator iter;
for (iter it = a.begin(); it != a.end(); ++it)
std::cout << *it << std::endl;
}
int main()
{
IntArray a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
printArray(a);
return 0;
}
问了谷歌一个小时后,我不知道发生了什么事。
TArray
是一个从属名称,所以你需要像这样使用typename
:
typedef typename TArray::iterator iter;
这个“应该”(著名的遗言)在MSVC中也起作用
我记得有一本书非常透彻地解释了这一点:
TArray
是一个从属名称,因此您需要像这样使用typename
:
typedef typename TArray::iterator iter;
这个“应该”(著名的遗言)在MSVC中也起作用
我记得有一本书非常透彻地解释了这一点:
如果我没有弄错的话,MSVC++甚至在模板中的一些非依赖名称上接受
typename
。我认为这不需要诊断。如果我没有弄错的话,MSVC++甚至在模板中的一些非依赖名称上接受typename
。我认为这不需要诊断。@Casey,我认为我的问题不是重复的,因为它是我的答案。@Casey,我认为我的问题不是重复的,因为它是我的答案。