读书人

大牛们快来,一个跟模板构造函数有关的

发布时间: 2013-03-04 17:22:12 作者: rapoo

大牛们快来,一个跟模板构造函数有关的问题
问题很简单,请看代码,只有一个类和一个main函数
#include <iostream>
#include <algorithm>
using namespace std;

class abc
{
public:
template<class T>
abc(T t,T t2){swap(t,t2);}
};

int main()
{
int a=1,b=2;
abc c(a,b);
cout<<"a="<<a<<",b="<<b<<endl;
system("pause");
return 0;
}
-----------------------------------------
abc c(a,b);这句话自动指定了int类型,但是当我要指定的是int&类型的时候发现错误
abc c<int&>(a,b);
这样指定类型在一般的成员函数的情况下是完全没问题的,但是当这是一个构造函数的情况下,
这句话就被归类为错误.
请问各位大牛,在不改变abc类中代码的情况下,如何能在调用该构造时指定是引用类型?
[解决办法]

引用:
楼上大大们,重载函数这个方法我是知道的,但是我是希望在不改变abc里面代码的情况下能够指定是int&类型或者让它自动解析成int&类型,我是想知道这样不改变abc代码能不能够解决问题...

你只需改一下abc的声名,不需要改里面的代码。
[解决办法]
试试用ref包装
需要c++11支持或者boost库
[解决办法]
一般地说,不行。构造函数不可显式指定模板参数。

但是仅就你这个例子而言,如果你实在不能改动abc的代码,又想用abc的话,可以做一个代理:

#include <iostream>
#include <algorithm>
using namespace std;

class abc
{
public:
template<class T>
abc(T t,T t2){swap(t,t2);}
};

struct int_proxy
{
int* p;

int_proxy(int& i) : p(&i){}
};

void swap( int_proxy& l, int_proxy& r )
{
std::swap(*l.p,*r.p);
}

int main()
{
int a=1,b=2;
int_proxy ia(a),ib(b);
abc c(ia,ib);
cout<<"a="<<a<<",b="<<b<<endl;
system("pause");
return 0;
}

读书人网 >C++

热点推荐