0

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?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • Did you mean to drop the inheritance in the second example? – juanchopanza Jun 16 '12 at 14:52
  • @juanchopanza Yes, I meant to drop it, because the example was from a real project where `Base` depends on many more template parameters, so that an inner `typedef` makes the code a little more readable. Readability was actually why I tried the inheritance in MSVC++, but it failed on g++. – TemplateRex Jun 16 '12 at 19:07
  • 1
    Same answer as [this question](http://stackoverflow.com/questions/7908248/using-this-keyword-in-destructor). – curiousguy Jul 18 '12 at 05:37

2 Answers2

1

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
-1

$ 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

jnhgfd
  • 1
  • Can you give some context as to what this means, and how it's relevant to the question? –  Jun 16 '12 at 16:31