geraldCelente geraldCelente - 1 month ago 15
C++ Question

template declaration of `typedef typename Foo<T>::Bar Bar'

I am encountering great difficulty in declaring a templated type as shown below.

#include <cstdlib>
#include <iostream>

using namespace std;


template <class T>
class Foo
{
typedef T Bar;
};

template <class T>
typedef typename Foo<T>::Bar Bar;




int main(int argc, char *argv[])
{

Bar bar;

Foo<int> foo;


system("PAUSE");
return EXIT_SUCCESS;
}


I get error

template declaration of `typedef typename Foo<T>::Bar Bar'


about line

template <class T>
typedef typename Foo<T>::Bar Bar;


I am doing this because I want avoid writing typename Foo::Bar throught my code.

What am I doing wrong?

Answer

The typedef declaration in C++ cannot be a template. However, C++11 added an alternative syntax using the using declaration to allow parametrized type aliases:

template <typename T>
using Bar = typename Foo<T>::Bar;

Now you can use:

Bar<int> x;   // is a Foo<int>::Bar
Comments