In C++0x, you can use the using keyword to inherit constructors, like so:
class B { B(int) {} };
class A : public B { using B::B; };
Which will implicitly declare an A(int) constructor. Does this work with templates?
class B { B(int) {} };
template<class T> class A : public T { using T::T; };
Within T::T, I expect the compiler to figure out the left hand T since using the scope operator on template arguments is normal, but figuring out that the right hand T is the constructor is a special case. In fact it appears there’s an ambiguity: what if I have a method called T in B that I’m trying to add overloads to in A (that’s how a compiler would interpret such a using declaration pre-C++0x)?
Yes it works, and the reason is the name lookup mechanism. The mechanism a inheriting-constructors declaration works is simple: If the using declaration’s name refers to base class constructors, that’s an inheriting constructors declaration. At 3.4.3.1[class.qual]p2 we find:
This is the paragraph that makes out of class constructor definitions work, and this is also the paragraph that makes inheriting constructor declarations work. The second bullet applies in this case:
The latter example proves also useful in cases such as the following
In summary:
The first bullet above is a semantic rule – if the name after the nested name specifier refers to the injected class name (
B::Bormytype::B), then it will be translated to refer to the constructor(s).The second bullet is a syntactic rule – the names just must match – their meaning is irrelevant otherwise – there could have been a member called
Basein the template argument provided toX, such as in the following, but the using declaration would still import the constructors and do not name the memberBase: