我有一个关于 C++ 中特定模板友谊的问题。在C++ Primer一书中,具体的模板友情是这样写的:
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>
在friend语句中的类或函数名之后。
但是,在实践中,如果我这样写:
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