我在VC2010中有一个代码,我已经简化为一个小例子。
Test.h:
#pragma once
template <typename TPixel>
struct Image
{
typedef TPixel PixelType;
};
template <typename TImageType>
struct Operation
{
void DoOperation()
{
ImageType::PixelType value = 0;
// I've done a misprint here. It should be TImageType::PixelType
}
};
Test.cpp:
void Test()
{
typedef Image<char> ImageType;
Operation<ImageType> op;
op.DoOperation();
}
正如我所料,这会产生错误。
test.h(14): error C2653: 'ImageType' : is not a class or namespace name
现在,让我们稍微改变test.cpp
。
typedef Image<char> ImageType;
void Test()
{
Operation<ImageType> op;
op.DoOperation();
}
现在编译!令人惊讶的是,ImageType
中的DoOperation()
现在与test.cpp
中的全局typedef匹配。
我的问题:为什么要编译?这是Visual C ++错误还是标准行为?
答案 0 :(得分:3)
我认为test.cpp
包含test.h
之前 typedef,所以它实际上是
#include "test.h"
typedef Image<char> ImageType;
void Test()
{
Operation<ImageType> op;
op.DoOperation();
}
像这样完成,它确实是一个关于两阶段查找的错误或标准的不合规行为。应该相对于模板的声明点解析不依赖于模板参数的名称。