Is it possible to use the "using" declaration with template base classes? I have read it isn't here but is that because of a technical reason or is it against the C++ standard, and does it apply to gcc or other compilers? If it is not possible, why not?
Example code (from the link above):
struct A {
template<class T> void f(T);
};
struct B : A {
using A::f<int>;
};
To instantiate a template class explicitly, follow the template keyword by a declaration (not definition) for the class, with the class identifier followed by the template arguments. template class Array<char>; template class String<19>; When you explicitly instantiate a class, all of its members are also instantiated.
Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived. In this case, nested-name-specifier must name a base class of the one being defined.
A using declaration in a definition of a class A allows you to introduce a name of a data member or member function from a base class of A into the scope of A .
The obvious reason is that a using declaration and a using directive have different effects. A using declaration introduces the name immediately into the current scope, so using std::swap introduces the name into the local scope; lookup stops here, and the only symbol you find is std::swap .
What you linked to is a using directive. A using declaration can be used fine with templated base classes (haven't looked it up in the standard, but just tested it with a compiler):
template<typename T> struct c1 {
void foo() { std::cout << "empty" << std::endl; }
};
template<typename T> struct c2 : c1<T> {
using c1<T>::foo;
void foo(int) { std::cout << "int" << std::endl; }
};
int main() {
c2<void> c;
c.foo();
c.foo(10);
}
The compiler correctly finds the parameter-less foo
function because of our using-declaration re-declaring it into the scope of c2
, and outputs the expected result.
Edit: updated the question. here is the updated answer:
The article is right about that you are not allowed to use a template-id (template name and arguments). But you can put a template name:
struct c1 {
template<int> void foo() { std::cout << "empty" << std::endl; }
};
struct c2 : c1 {
using c1::foo; // using c1::foo<10> is not valid
void foo(int) { std::cout << "int" << std::endl; }
};
int main() {
c2 c;
c.foo<10>();
c.foo(10);
}
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