我在 VC2010 中有一段代码,我已将其简化为一个小示例。
测试.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
}
};
测试.cpp:
void Test()
{
typedef Image<char> ImageType;
Operation<ImageType> op;
op.DoOperation();
}
正如我所料,这会产生错误。
test.h(14): 错误 C2653: 'ImageType': 不是类或命名空间名称
现在,让我们稍微更改一下 test.cpp
。
typedef Image<char> ImageType;
void Test()
{
Operation<ImageType> op;
op.DoOperation();
}
现在可以编译了!令人惊讶的是,DoOperation()
中的 ImageType
现在与 test.cpp
中的全局 typedef 匹配。
我的问题:为什么它能编译?这是 Visual C++ 错误还是标准行为?
最佳答案
我认为 test.cpp
包含 test.h
在 typedef 之前,所以它实际上是
#include "test.h"
typedef Image<char> ImageType;
void Test()
{
Operation<ImageType> op;
op.DoOperation();
}
这样完成,它确实是一个错误,或者是关于两阶段查找的标准不合格行为。不依赖于模板参数的名称应相对于模板的声明点进行解析。
关于c++ - 模板类的方法使用全局范围内的 typedef。编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10948079/