Question

The code below does not compile on Ideone or Codepad, yielding errors like:

'X' was not declared in this scope

but it does on 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;
    }

where it prints int, char and float. Should I change my code to:

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

in order to be standard-conforming?

Was it helpful?

Solution

If you meant the equivalent of this (note you have dropped the inheritance in your example):

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

then yes, that is standard compliant code. But note that the result of typeid(some type).name() is implementation dependent. On GCC your main produces i, c and f.

OTHER TIPS

$ g++ -Wall test.cpp
test.cpp: In static member function 'static void Derived::print()':
test.cpp:15:37: error: 'X' was not declared in this scope

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top