0

下面的代码不能在 Ideone 或 Codepad 上编译,产生如下错误:

'X' 未在此范围内声明

但在 VC++ 2010 上确实如此:

    #include <iostream>
    #include <typeinfo>

    template<typename T>
    struct Base
    {
            typedef T X;
    };

    template<typename T>
    struct Derived
    :
            Base<T>
    {
            static void print()
            {
                    std::cout << typeid(X).name() << "\n";
            }
     };

    int main()
    {
            Derived<int>::print();
            Derived<char>::print();
            Derived<float>::print();
            return 0;
    }

它在哪里打印int和。我应该将代码更改为:charfloat

    template<typename T>
    struct Derived
    {
            typedef Base<T> B;
            static void print()
            {
                    std::cout << typeid(typename B::X).name() << "\n";
            }
     };

为了符合标准?

4

2 回答 2

1

如果您的意思是等效的(请注意,您已在示例中删除了继承):

template<typename T>
struct Derived : Base<T>  {
  static void print() {
    std::cout << typeid(typename Base<T>::X).name() << "\n"; 
  }
};

那么是的,这是符合标准的代码。但请注意,结果typeid(some type).name()取决于实现。在 GCC 上,您的主要产品i,cf.

于 2012-06-16T15:04:45.573 回答
-1

$ g++ -Wall test.cpp
test.cpp:在静态成员函数'static void Derived::print()'中:
test.cpp:15:37:错误:'X'未在此范围内声明

$ g++ --version
g++ (SUSE Linux) 4.6.2

于 2012-06-16T14:03:27.513 回答