我對C++中特定模板友誼有疑問。書中C++入門 ,具體的模板友誼是這樣寫的:C++中的特定模板友誼
template <class T> class Foo3;
template <class T> void templ_fcn3(const T&);
template <class Type> class Bar {
// each instantiation of Bar grants access to the
// version of Foo3 or templ_fcn3 instantiated with the same type
friend class Foo3<Type>;
friend void templ_fcn3<Type>(const Type&);
// ...
};
特殊的一點是,有
<Type>
在朋友聲明的類或函數名後。
然而,在實踐中,如果我這樣寫:
template <class Type> class T_CheckPointer;
template <class T> T_CheckPointer<T> operator+(const T_CheckPointer<T> &, const size_t n);
template <typename Type>
class T_CheckPointer {
// Specific Template Friendship
friend T_CheckPointer<Type>
operator+ <Type> (const T_CheckPointer<Type> &, const size_t n);
// other code...
}
將有實例爲模板函數時的錯誤。
如果我在函數名後刪除字型改變
// Specific Template Friendship
friend T_CheckPointer<Type>
operator+ <Type> (const T_CheckPointer<Type> &, const size_t n);
到
// Specific Template Friendship
friend T_CheckPointer<Type>
operator+ <> (const T_CheckPointer<Type> &, const size_t n);
,然後一切都會好起來的。
任何人都可以告訴我原因嗎?
的信息,還有就是錯誤信息當我打電話
int iarr[] = {1, 2, 3, 4};
T_CheckPointer<int> itcp(iarr, iarr+4);
錯誤消息:
/usr/include/c++/4.4/bits/stl_iterator_base_types.h: In instantiation of ‘std::iterator_traits<int>’:
/usr/include/c++/4.4/bits/stl_iterator.h:96: instantiated from ‘std::reverse_iterator<int>’
../Classes/T_CheckPointer.hpp:31: instantiated from ‘T_CheckPointer<int>’
../PE16.cpp:520: instantiated from here
/usr/include/c++/4.4/bits/stl_iterator_base_types.h:127: error: ‘int’ is not a class, struct, or union type
/usr/include/c++/4.4/bits/stl_iterator_base_types.h:128: error: ‘int’ is not a class, struct, or union type
/usr/include/c++/4.4/bits/stl_iterator_base_types.h:129: error: ‘int’ is not a class, struct, or union type
/usr/include/c++/4.4/bits/stl_iterator_base_types.h:130: error: ‘int’ is not a class, struct, or union type
/usr/include/c++/4.4/bits/stl_iterator_base_types.h:131: error: ‘int’ is not a class, struct, or union type
什麼是錯誤信息? – enobayram
@enobayram,感謝您的關注,我把它們放在文章中。 – Tianyi
你能提供一個**最小**的例子(例如編譯)。Ideone)顯示問題?你有沒有嘗試升級到GCC 4.7? – TemplateRex