Inheritance and patterns in C ++ - why are methods invisible?

When a template is publicly inherited from another template, aren't publicly available public methods available?

template <int a> class Test { public: Test() {} int MyMethod1() { return a; } }; template <int b> class Another : public Test<b> { public: Another() {} void MyMethod2() { MyMethod1(); } }; int main() { Another<5> a; a.MyMethod1(); a.MyMethod2(); } 

Well, GCC shit on this ... I need to miss something completely obvious (brain melt). Help?

+18
c ++ inheritance templates
Oct 14 '09 at 17:17
source share
5 answers

This is part of the rules for dependent names. Method1 not a dependent name in the scope of Method2 . Therefore, the compiler does not look for it in dependent base classes.

There are two ways to fix this: Using this or specifying a base type. Learn more about this recent post or to the C ++ FAQ . Also note that you missed the public keyword and half-time. Here is a fixed version of your code.

 template <int a> class Test { public: Test() {} int MyMethod1() { return a; } }; template <int b> class Another : public Test<b> { public: Another() {} void MyMethod2() { Test<b>::MyMethod1(); } }; int main() { Another<5> a; a.MyMethod1(); a.MyMethod2(); } 
+27
Oct. 14 '09 at 17:25
source share

You must fully qualify MyMethod1 . The C ++ standard clearly states this in 14.6.2 / 3:

In the definition of a class template or member of a class template, if the base class of the class template depends on the template parameter, the scope of the base class is not considered when searching for an unqualified name either at the definition point of the template or member of the class or while creating the template or member of the class.

So you should write:

 void MyMethod2() { Test<b>::MyMethod1(); } 
+12
Oct. 14 '09 at 17:43
source share

main needs a return type.

The Other class needs a final half-colony.

class It is still necessary that its members are publicly available.

In addition, methods are generally not considered invisible; methods were not available without the open access keyword.

+2
Oct. 14 '09 at 17:23
source share

I cleared your code before this:

 template <int a> class Test { public: Test() {} int MyMethod1() { return a; } }; template <int b> class Another : public Test<b> { public: Another() {} void MyMethod2() { MyMethod1(); } }; int main() { Another<5> a; a.MyMethod1(); a.MyMethod2(); } 

And compiled with -fpermissive without any problems (maybe you can solve this problem).

+1
Oct 14 '09 at 17:23
source share

I think you just skipped the post: at the top of another definition. For such questions, it is usually helpful to post the error messages you receive.

0
Oct. 14 '09 at 17:22
source share



All Articles