Re: What's the best way to do this...? (templates/inheritance problem)
fungus wrote:
I've got a big template class "A" and I want to write another template
"B" which is exactly the same as A except for one method (let's call
it "foo()").
Is there a way to do this without complete copy/paste of "A"? I'd like
to do it with only one copy of the common code.
Is that a trick question? The first rule of the class hierarchy:
if two classes are very similar except for some minor differences,
extract the common portion into a separate class and make your two
classes inherit that.
It goes the same for class templates. The common functionality has
to be extracted into another template. Both class templates inherit
from that [base] template.
nb. foo() can't be static, it needs access to class members....
template <class T> class A {
void foo();
};
template <class T> class B {
void foo(); // I want a different "foo()" here...
};
On a related note, something which came up while I was messing around
with this is that when I inherit from a class ("A"), all the
constructors in "A" are hidden.
Not hidden. The constructors are special function that are never
_inherited_ .
class A {
public:
A(int);
};
class B : public A {
public:
// Compiler writes a constructor for me, hiding A(int)...
};
main() {
// Doesn't work...compiler says 'int' can't be converted to 'const
B&'
B b(42);
}
How can I make A's constructors visible?
You cannot. You can only create a constructor in 'B' that will
take one argument and simply forward it to the base class' c-tor.
See "initialisation of base classes" in your favourite C++ book.
I read the faq and tried
adding
a "using A::A", but it makes no difference...
class B : public A {
public:
using A::A; // Makes no difference...
};
faq:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask