读书人

类模板中的成员函数模板的正确使用方法

发布时间: 2012-05-05 17:21:10 作者: rapoo

类模板中的成员函数模板的正确使用方法难道不是这样的吗?

C/C++ code
类模板中的成员函数模板的正确使用方法:函数模板也需要指名类型,类模板也要指名。好像只有这种正确方法吧,其他都不对吧。以下是个演示: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???....................... }


[解决办法]
不指明会从调用实参的类型中推导模板形参类型。
C/C++ code
template<class T2>void fun()
[解决办法]
我一直是下面这么写的,应该对的吧。

template<typename Type>
class A
{
public:
void fun();
};

template<typename Type>
void A<Type>::fun()
{
cout << "hellow!" << endl;
}

调用的时候:

A<int> a;
a.fun();
A<double> b;
b.fun();

当然在这里例子没有具体的数值体现不同的类型。

读书人网 >C++

热点推荐