Calling a base class method in a hierarchy of template virtual classes

Let's say I have the following class hierarchy:

template< class T > class TestBase { public: virtual T const & do_foo() = 0; }; template< class T > class TestDerived : public virtual TestBase< T > { public: virtual int do_bar() { return do_foo() + 1; } }; 

GCC spits out the following:

 error: there are no arguments to 'do_foo' that depend on a template parameter, so a declaration of 'do_foo' must be available [-fpermissive] note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated) 

Now, if I change this to get from a test base created from a known type (for example, class TestDerived : public virtual TestBase< int > , this fragment compiles just fine, so the problem seems to be related to the type of base the class is unknown at compile time.I did not create objects of any class anywhere, I do not understand why this should even matter.

Basically, how can I fix the error without resorting to -fpermissive ?

+4
source share
2 answers

Independent names (that is, names that are independent of the template arguments) are looked up when the template is parsed, and now when it is created. You need to make do_foo dependent name. There are two ways to achieve this:

 virtual int do_bar() { return this->do_foo() + 1; } 

or

 template< class T > class TestDerived : public virtual TestBase< T > { public: using TestBase<T>::do_foo; virtual int do_bar() { return do_foo() + 1; } }; 
+7
source

He will not win any beauty awards, but this piece of code works as expected without a compiler complaining.

 virtual int do_bar() { return ((TestBase<T> *) this)->do_foo() + 1; } 
-1
source

All Articles