0

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

I have a class that creates a smart pointer when creating a object and passing the desired class as template parameter. And I have another class that needs to use that smart pointer in another class.

#include <iostream>
using namespace std;

//smart pointer class

template<typename T>
class IntrusivePtr
{
public:
    IntrusivePtr()
    {
        cout << "IntrusivePtr()";
    }
};

//class for which I need a smart pointer which is also template

template<typename T>
class A
{
public:
    A()
    {
        cout << "A()";
    }
    typedef IntrusivePtr< A<T> > my_ptr;
};

//class that uses the smart pointer.

template<typename T>
class B
{
public:
    B()
    {
        cout << "B()";
    }

    typedef A<T>::my_ptr x;
};



int main()
{
    B<int> ob;

    return 0;
}

Can this be achieved in c++? I know the new C++11 supports typedefs for things like this but I'm using the old standard :( Compiling this I'm getting some bad ass errors:

C:\Users\jacob\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop_-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: error: C2146: syntax error : missing ';' before identifier 'x'

C:\Users\jacob\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop_-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: error: C2146: syntax error : missing ';' before identifier 'x'

C:\Users\jacob\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop_-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: error: C4430: missing type specifier - int assumed. Note: C++ does not support default-int

EDIT: Sorry, I changed some things and the error code. This is how I want it to be. Sorry

Jacob Krieg
  • 2,430
  • 10
  • 60
  • 114

2 Answers2

3
template<typename T>
class B
{
public:
    B()
    {
        cout << "B()";
    }

    typedef typename A< B >::my_ptr x;
};

You should use typename, since my_prt is dependent name.

ForEveR
  • 52,568
  • 2
  • 101
  • 125
3

Your problem is that A<B>::my_ptr is a dependend name (it depends on B<T> and therefore on the template parameter T). For this reason the compiler doesn't know if it is supposed to be a type or a variable when parsing the template. In that situation it assumes that my_ptr is not a type, unless you explecitely tell it so. Therefore you need to add typename, just like the compiler told you to do:

typedef typename A< B >::my_ptr x;

For a more complete explanation look at this answer to a similar question.

Community
  • 1
  • 1
Grizzly
  • 18,279
  • 3
  • 56
  • 75