Home Why when a template class inherits from another template class, typedefs need to be respecified and functions calls qualified?
Reply: 0

Why when a template class inherits from another template class, typedefs need to be respecified and functions calls qualified?

user7816
1#
user7816 Published in September 19, 2018, 9:57 am

When a template class inherits from another template class, typedefs in the base class must be redefined again (i.e. they are not automatically inherited), and function calls in the base class need to be qualified. Why is that? Isn't this already unambiguous?

So if I have 20 template classes, all defining the same typedefs, I am not able to introduce a base class containing these definitions them and inherit from it, as I have to redefine the typedefs anyway in every class, which defeats the purpose. This is makes the source code so unnecessarily verbose.

I can see this has been discussed in this question, but I do not understand the comment

The C++ name lookup rules specify that a name is only searched in a templated base classes if it depends on a template parameter (if it is a "dependent name"). If a name does not depend on a template parameter it isn't searched there.

What is the reason for this? It makes no sense to me.

Perhaps, the following code snippet would illustrate my question better:

#include <iostream>

template <unsigned N, typename T>
struct A
{
   typedef T U;
   static void foo(T x) { std::cout << N + x << "\n"; }
};

template <unsigned N, typename T>
struct B : public A<N, T>
{
    // Why do I have to redeclare U? Isn't is unambiguous already?
    typedef typename A<N, T>::U U;

    //  why do I have to specify B::? Isn't it unambiguous already?
    static void zoo(U x) { B::foo(x); }  
};

int main()
{
    B<2,int>().zoo(3);
    B<2,double>().zoo(3.5);
    return 0;
}
share|improve this question
  • I have recently run into this as well and found it quite odd, one note instead of "typedef typename A<N, T>::U U;" you could make a typedef for the base(something I often find useful with template bases) and then have a using: typedef A<N, T> base_type; using typename base_type::U; – SoronelHaetir Jan 11 at 5:31
  • Thanks, I am aware of that. The downside is that you have to use typename base_type:: all over the places. Expressions becomes verbose polluted with useless keywords. – Fabio Jan 11 at 5:47

2 Answers 2

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.442072 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO