Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 951
geraldCelente Avatar asked Oct 04 '13 23:10

geraldCelente


People also ask

What is typename in template?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.

What is the difference between template typename T and template T?

There is no difference. typename and class are interchangeable in the declaration of a type template parameter.

Is template a keyword in C++?

C++ template is also known as generic functions or classes which is a very powerful feature in C++. A keyword “template” in c++ is used for the template's syntax and angled bracket in a parameter (t), which defines the data type variable.

What is the difference between class and typename in template?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.


2 Answers

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 
like image 131
Kerrek SB Avatar answered Oct 26 '22 16:10

Kerrek SB


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; 
like image 39
Praetorian Avatar answered Oct 26 '22 16:10

Praetorian