-
December 15th, 2008, 08:58 PM
#1
template inheritance when base's members initialize derived members
Hi!
The question is about template inheritance when base's members are supposed to initialize the derived members. The following code works fine but if one removes comments it returns an error. The problem, as far as i understand, is that the template does not generate actual type at definition, therefore members of the base template cannot initialize members of the derived template. Is there some beautiful solution for this problem?
Code:
/*template <int dim>*/ class A {
protected:
int A_a;
public:
A (int arg) : A_a(arg) {}
};
/*template <int dim>*/ class B : public A/*<dim>*/ {
protected:
int B_b;
public:
B (int arg) : B_b(A_a), A/*<dim>*/(arg) {}
};
int main () {
B/*<2>*/ x(3);
}
Last edited by StudentFS; December 15th, 2008 at 09:05 PM.
-
December 15th, 2008, 09:05 PM
#2
Re: template inheritance when base's members initialize derived members
1) Get rid of the comments and other extraneous characters
2) Post your code using code tags so that it becomes readable.
Regards,
Paul McKenzie
-
December 15th, 2008, 09:09 PM
#3
Re: template inheritance when base's members initialize derived members
Thanks, done. Comments in the code are significant for the question.
-
December 15th, 2008, 09:12 PM
#4
Re: template inheritance when base's members initialize derived members
As to the answer to your question, this code compiles correctly. Note the changes made in red:
Code:
template <int dim>
class A {
protected:
int A_a;
public:
A (int arg) : A_a(arg) {}
};
template <int dim>
class B : public A<dim>
{
protected:
int B_b;
public:
B (int arg) : B_b(this->A_a), A<dim>(arg) {}
};
int main () {
B<2> x(3);
}
There are two solutions, and one is what I gave above. Here is the pertinent link as to why this works:
http://www.parashift.com/c++-faq-lit...html#faq-35.18
http://www.parashift.com/c++-faq-lit...html#faq-35.19
Regards,
Paul McKenzie
-
December 15th, 2008, 09:14 PM
#5
Re: template inheritance when base's members initialize derived members
That's great! Thank you very much!
-
December 16th, 2008, 02:20 AM
#6
Re: template inheritance when base's members initialize derived members
AFAIK, inheritance is off by default for template. In other words, function name in base class is hided in derived class. There are several solution to this. Why is point of this program ?
1. using directive.
2. Explicit qualified name.
3. this pointer
I think(guess) this pointer only applicable to Is-a relationship.
Thanks for your help.
Thanks for your help.
-
December 16th, 2008, 07:38 PM
#7
Re: template inheritance when base's members initialize derived members
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|