虚拟朋友功能和模板显式特化

时间:2011-02-22 14:27:23

标签: c++ templates inheritance virtual

我正在尝试使用受保护的虚拟成员函数来模拟虚拟朋友函数的效果(http://www.parashift.com/c++-faq-lite/friends.html#faq-14.3)。 另外,我对模板化的类使用显式特化。我想知道是否有人可以解释一下我做错了什么。 下面,我发布了编译错误的代码。欢迎任何建议!

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

2 个答案:

答案 0 :(得分:3)

refFoo.do_applyOnBar(refBar); // error

由于refFoo是对const CFoo的引用,因此它不能用于调用非const函数。 do_applyOnBar是非const成员函数。

因此,要么通过在函数签名的右侧写入关键字d_applyOnBar来使const成为const函数,要么通过删除{{1来使refFoo成为非const。参数声明中的限定符!

Erik指出了另一个问题。看他的回答!

答案 1 :(得分:2)

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

缺乏&amp;关于第二个论点,应该是:

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

接下来,

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

这个需要一个const,因为你使用refFoo.do_applyOnBar(refBar);和refFoo是const。

virtual void do_applyOnBar(const CBar<U> &) const;
相关问题