C++ 中模板函数的默认参数的简单分析

博客介绍了C++中template可声明函数模板和类模板,重点讲解template中参数默认值的使用。通过例1指出直接在函数声明处给参数赋默认值无法编译;例2表明给模板函数类型赋默认值可正常生成函数;例3说明类模板函数无此问题,因其须指明模板参数类型。

C++中的 template 可以用来声明函数模板和类模板,讲到函数模板,就难免想到参数默认值。

以下是几个例子,用来说明,template中参数默认值的使用。

    1. 按照最初的设想,直接在函数声明处给参数赋默认值。无法通过编译,会提示无法找到对应的函数声明。如例1。
    2. 发现是无法生成默认值对应的模板函数,给模板函数的类型也赋默认值后,能够正常生成形如void print(T, Ts&)的函数。其中,类型Ts的默认值要与参数os的默认值相符合。如例2。
    3. 对于类模板中的函数,则不存在类似的问题。因为类模板必须指明模板参数的类型。如例3。

例1:

#include<iostream>
using namespace std;

template<typename T,typename Ts>//没有给Ts赋默认值
void print(T input,Ts& os=cout){
    os<<input<<endl;
}

int main(){
    print("hello template");
    return 0;
}

编译报错如下:

test4template.cpp: In function ‘int main()’:
test4template.cpp:11:24: error: no matching function for call to ‘print(const char [15])’
  print("hello template");
                        ^
test4template.cpp:6:6: note: candidate: template<class T, class Ts> void print(T, Ts&)
 void print(T input,Ts& os=cout){
      ^
test4template.cpp:6:6: note:   template argument deduction/substitution failed:
test4template.cpp:11:24: note:   couldn't deduce template parameter ‘Ts’
  print("hello template");
                        ^

例2:

#include<iostream>
using namespace std;

template<typename T,typename Ts=ostream>
void print(T input,Ts& os=cout){
    os<<input<<endl;
}

int main(){
    print("hello template");
    return 0;
}

能够正常编译运行,运行结果如下:

hello template

按回车键返回

例3:

#include<iostream>
using namespace std;

template<typename T,typename Ts=ostream>
void print(T input,Ts& os=cout){
    os<<input<<endl;
}
template<typename T,typename Ts>
class printDao{
public:
    printDao(){}
    
    static void print(T input,Ts& os=cout){
        os<<input<<endl;
    }
};

int main(){
    print("hello template");
    
    printDao<string,ostream> p;
    p.print("hello template in class");
    return 0;
}

运行结果:

hello template
hello template in class

按回车键返回

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值