如果引用参数是const,(如:func(const double &ra))则编译器将在下面两种情况下生产临时变量:
1. 实参的类型正确,但不是左值。(如:7.0、temp+7等)
2. 实参的类型不正确,但可以转换为正确的类型。(如:int,long等)
C++11新增了另一种引用——右值引用。这种引用可以指向右值,是使用&&声明的:
double && rref = sqrt(36.0);
double && jref = 2.0*j + 18.5;
double m = sqrt(16.0);
cout << sqrt(25.0);
第一条语句中,值4.0被复制到一个临时位置,然后被复制给m。
第二条语句中,值5.0被复制到一个临时位置,然后被传递给cout。
若返回引用,则直接把值复制到m中,更加高效。
string version(const string& s1, const string& s2){...} //函数声明
string input = "absc";
version(input, "***"); //调用
//函数原型
char * left(const char* str, int n=1);
//函数定义
char * left(const char* str, int n)
{...}
void func(double &r1);
void func(const double &r2);
void func(double && r3);
double x = 55.5;
const double y = 12.2;
func(x); //调用void func(double &r1);
func(y); //调用void func(const double &r2);
func(x+y); //调用void func(double && r3);
若没有void func(double && r3);那么func(x+y)将会调用void func(const double &r2);
long func(int,float);
//内部表示来描述该接口
?func@@YAXH
对原始名称进行的表面看来无意义的修饰将对参数数目和类型进行编码。添加的一组符号随函数特征标而异,而修饰时使用的约定随编译器而异。
templateT>
void Swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
//模板函数
template <typename T>
void Swap(T&, T&){}
//显示具体化函数
template<> void Swap(job&, job&){}
template void Swap(int, int);
实现了这种特性的编译器看到上述声明后,将使用Swap()模板生成一个使用int类型的实例。或者直接Swap(d1, d2);
template<> void Swap(job&, job&){...}
template T>
void Swap(T&, T&);
template <> void Swap(job&, job&) //显示具体化
{
...
}
int main()
{
template void Swap(char &, char &); //显示实例化
short a,b;
...
Swap(a,b); //使用模板,隐式实例化
...
job n,m;
...
Swap(n,m); //使用显示具体化
char g,h;
...
Swap(g,h); //使用显示实例化
}
决定函数调用哪个函数定义,尤其是有多个参数时,称为重载解析。
从最佳到最差的顺序如下:
1. 完全匹配:常规函数优先于模板。
2. 提升转换:(例如char和shorts自动转换成为int, float自动转换为double)
3. 标准转换:(例如int转换成为char,long 转换为double)
4. 用户定义转换。如类声明中定义的转换。
无关紧要的转换:
有时候即使两个函数都完全匹配,有可以完成重载解析。首先,指向非const数据的指针和引用优先于非const指针和引用参数匹配。其次,非模板优先于模板。
template <class Type>
void recycle(Type t);
//
template <class Type>
void recycle(Type* t);
//
int bolt = 12;
recycle(&bolt); //虽然两个模板都可以,但将调用第二个模板,因为更具体。
template
void ft(T1 x, T2 y)
{
...
?Type? xpy = x + y;
...
}
int x;
decltype(x) y; //make y the same type as x
//解决问题
decltype(x+y) xpy;
xpy = x + y;
//合二为一
decltype(x+y) xpt = X + y;S
auto res = x + y;