64,648
社区成员
发帖
与我相关
我的任务
分享
类模板中的成员函数模板的正确使用方法:函数模板也需要指名类型,类模板也要指名。好像只有这种正确方法吧,其他都不对吧。
以下是个演示:
template<class T>
class A
{
public:
template<class T2>
void fun()
{
cout<<"hello c++!"<<endl;
}
};
A a<int>;
a.fun<double>(); //函数要指名类型的。。
但是发现vector的一段代码不是这样,感觉很奇怪。。
template<class T, class Alloc=alloc>
class vector
{
template <class ForwardIterator>
iterator allocate_and_copy(size_type n,
ForwardIterator first, ForwardIterator last) ;
..............
};
使用模板函数:allocate_and_copy也应该指出类型才对啊。。。
但是下面这段代码没有指名,就是用了。
vector(const vector<T, Alloc>& x) {
start = allocate_and_copy(x.end() - x.begin(), x.begin(), x.end());
//直接传参数,x.end()类型是iterator,谁来执行函数类型是:iterator???
.......................
}
template<class T2>
void fun()
template<class T2>
void fun(T2);
a.fun(2.0); // T2 will be deduced as double on this call