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?
" 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.
There is no difference. typename and class are interchangeable in the declaration of a type template parameter.
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.
There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With