【问题标题】:Method of a template class uses a typedef from the global scope. Compiler bug?模板类的方法使用全局范围的 typedef。编译器错误?
【发布时间】:2012-06-08 11:36:04
【问题描述】:

我在 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();
  }

现在它编译了!令人惊讶的是,DoOperation() 中的 ImageType 现在与 test.cpp 中的全局 typedef 匹配。

我的问题:它为什么会编译?这是 Visual C++ 错误还是标准行为?

【问题讨论】:

    标签: c++ templates visual-c++


    【解决方案1】:

    我认为test.cpp 包含test.h typedef 之前,所以它实际上是

    #include "test.h"
    typedef Image<char> ImageType;
    
    void Test()
      {
      Operation<ImageType> op;
      op.DoOperation();
      }
    

    这样完成,确实是一个错误,或者关于两阶段查找的标准不合格行为。不依赖于模板参数的名称应该相对于模板的声明点进行解析。

    I guess this is known behavior.

    【讨论】:

    • 看了你提供的链接后,我同意你的看法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多