Virtual friend functions and template explicit specializations
我试图通过使用受保护的虚拟成员函数(http://www. PARASIFIF.COM/C++-FAQLIT/FALID.HTML*FAQ-143)来模拟虚拟友元函数的效果。此外,我对模板类使用显式专用化。我在想,是否有人能对我做错了什么有所了解。下面,我将发布带有编译器错误的代码。欢迎提出任何建议!
福奥1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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> &); ..... }; |
英尺·CPP
1 2 3 4 5 6 7 8 9 10 | 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" |
福奥公司
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
1 | refFoo.do_applyOnBar(refBar); // error |
由于
因此,要么通过在函数签名的右侧写入关键字
埃里克指出了另一个问题。看他的答案!
1 | template < class T, class U > void applyOnBar( const CFoo<T, U> &, const CBar<U> ); |
在第二个论点上缺少的,应该是:
1 | template < class T, class U > void applyOnBar( const CFoo<T, U> &, const CBar<U> & ); |
下一步,
1 | virtual void do_applyOnBar(const CBar<U> &); |
这个需要一个常量,因为使用
1 | virtual void do_applyOnBar(const CBar<U> &) const; |