Pergunta

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?

Foi útil?

Solução

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

Outras dicas

typedef's cannot be templates. This is exactly the reason C++11 invented alias templates. Try

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

You can't typedef a template. However, you can use an alias template. The code below demonstrates the use and fixed a few other problems, too:

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

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

int main(int argc, char *argv[])
{
    Bar<int> bar;
    Foo<int> foo;
}

Hope it's okay to add late answers...

I'm still using VS2012 which does not appear to implement alias templates, so I resorted to this concoction for my purposes:

//map<CWinThread*, AKTHREADINFO<T> > mapThreads;   // won't compile
#define MAP_THREADS(T) map<CWinThread*, AKTHREADINFO<T> >

...

MAP_THREADS(T) mapThreads;

Sorry it does not demonstrate the original example, but you get the drift.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top