In the following setup, how can I make it so that I can refer to the name Bar
inside the derived class Derived<T>
?
template <typename T> struct Foo
{
template <typename U> struct Bar { };
};
template <typename T> struct Derived : Foo<T>
{
// what goes here?
Bar<int> x; // Error: 'Bar' does not name a type
};
I've tried using Foo<T>::Bar;
, but that doesn't help. Is there any sort of using
declaration that can make the name of a nested base template known to the derived class, so that I can keep the simple declaration Bar<int> x
?
I know that I can say typename Foo<T>::template Bar<int> x;
, but I have a lot of those cases and I don't want to burden the code needlessly with so much verbosity. I also have a lot of distinct "int
s", so a typedef
for each nested-template instance is not feasible, either.
Also, I cannot use GCC 4.7 at this point nor C++11, and would thus like a "traditional" solution without template aliases.
In C++11 you can use an alias template:
template <typename T> struct Derived : Foo<T>
{
template<typename X> using Bar = typename Foo<T>::template Bar<X>;
Bar<int> x;
};
Edit
The traditional solution is what you're already said, typename Foo<T>:template Bar<int>
, or to emulate a "template typedef"
template <typename T> struct Derived : Foo<T>
{
template<typename X>
struct Bar
{ typedef typename Foo<T>::template Bar<X> type; };
typename Bar<int>::type x;
};
One of the reasons for adding alias templates to the language is they support things which can't be expressed easily in C++03.