Search code examples
c++templatesinheritancevirtual

Virtual friend functions and template explicit specializations


I'm trying to simulate the effect of a virtual friend function by using a protected virtual member function (http://www.parashift.com/c++-faq-lite/friends.html#faq-14.3). In addition, I use explicit specializations for my templated classes. I was wondering if somebody could shed some light to understand what I'm doing wrong. Below, I'm posting the code with the compiler errors. Any suggestions are welcomed!

foo.h

template < class T, class U >
class CFoo;

template < class T, class U >
void applyOnBar( const CFoo<T, U> &, const CBar<U> );

template < class T, class U >
class CFoo{

    public:
        .....
        friend void applyOnBar< >( const CFoo<T, U> &, const CBar<U> & ); // error, line 28: function does not match any template declaration.
        .....
        virtual ~CFoo();

    protected:

        virtual void do_applyOnBar(const CBar<U> &);
        .....
};

foo.cpp

template < class T, class U >
void applyOnBar( const CFoo<T, U> & refFoo, const CBar<U> & refBar ){
    refFoo.do_applyOnBar(refBar); // error, line 36: passing argument first argument discards qualifiers.
}

template < class T, class U >
void CFoo<T, U>::do_applyOnBar( const CBar<U> & refBar ){  // error, line 40: member function is protected.
    ......
}
#include "../impl/foo-impl.inc"

foo-impl.inc

template class CFoo<float, float>; // line #1
.....
template void applyOnBar(const CFoo<float, float> &, const CBar<float> &); // line #6

./inc/foo.h: In instantiation of ‘CFoo<float, float>’:  
./src/../impl/foo-impl.inc:1:   instantiated from here  
./inc/foo.h:28: error: template-id ‘applyOnBar<>’ for ‘void applyOnBar(const CFoo<float, float>&, const CBar<float>&)’ does not match any template declaration  

./src/foo.cpp: In function ‘void applyOnBar(const CFoo<T, U>&, const CBar<U>&) [with T = float, U = float]’:  
./src/../impl/foo-impl.inc:6:   instantiated from here  
./src/foo.cpp:40: error: ‘void CFoo<T, U>::do_applyOnBar(const CBar<U>&) [with T = float, U = float]’ is protected  
./src/foo.cpp:36: error: within this context  
./src/foo.cpp:36: error: passing ‘const CFoo<float, float>’ as ‘this’ argument of ‘void CFoo<T, U>::do_applyOnBar(const CBar<U>&) [with T = float, U = float]’ discards qualifiers

Solution

  • template < class T, class U > void applyOnBar( const CFoo<T, U> &, const CBar<U> );
    

    That lacks an & on the second argument, should be:

    template < class T, class U > void applyOnBar( const CFoo<T, U> &, const CBar<U> & );
    

    Next,

    virtual void do_applyOnBar(const CBar<U> &);
    

    This one needs a const, since you use refFoo.do_applyOnBar(refBar); with refFoo being const.

    virtual void do_applyOnBar(const CBar<U> &) const;