模板函数的模板参数、函数参数,模板类的模板参数、构造函数参数,重载非const调用操作符

本文探讨了C++中模板函数的使用,涉及模板参数、重载调用操作符,以及模板类的构造函数默认参数。特别强调了函数参数应为const对象引用的重要性。还介绍了如何处理非const类对象和重载非const调用操作符。
摘要由CSDN通过智能技术生成

        一、模板函数的模板参数,以重载调用操作符的类 及 函数指针作为模板参数的实参,其函数参数及函数参数的传参,测试代码如下:

#include <iostream>
using namespace  std;

//key
string s1("Hello");
string s2("World");

//重载了调用操作符的类其对象称为函数对象
class cmp{
public:
    bool operator()(const string& s1, const string& s2)const{
        cout << "bool operator()(const string& s1, const string& s2)const\n";
        return s1 < s2;
    }//类对象为const//成员函数为const//成员函数为const是防止修改类对象
};    

bool compare(const string& s1, const string& s2){
    cout << "bool compare(const string& s1, const string& s2)\n";
    return true;
}

template<typename Compare>     //模板类型
void test( const Compare&c = Compare() ){ //函数参数为const对象引用//默认值为函数对象//
                            //默认值为临时对象,右值,const对象的引用
    cout << "void test( const Compare&c = Compare() )\n";
    c( s1,s2 );
}

int main () 
{
    test<bool(*)(const string&, const string&) >(compare ); //函数指针//传参
    cout << "--------------------------------------\n"; 
    test<cmp>( );   //默认//函数对象Compare()

    return 0;
}

  模板函数的函数参数,默认为临时对象,应为const对象引用,因为 临时对象为右值

        二、模板类的模板参数 与 构造函数的默认参数

#include <iostream>
using namespace  std;

//key
string s1("Hello");
string s2("World");

//cmp
class cmp{
public:
    bool operator()(const string& s1, const string& s2)const{
        cout << "bool operator()(const string& s1, const string& s2)const\n";
        return s1 < s2;
    }//const
};    

bool compare(const string& s1, const string& s2){
    cout << "bool compare(const string& s1, const string& s2)\n";
    return true;
}

template<typename Compare>     //模板类
struct Test{
    Test( const Compare&c = Compare() ){
        cout << "Test( const Compare&c = Compare() )\n";
        c( s1,s2 );
    }
};

int main () 
{
    Test<bool(*)(const string&, const string&) > t1(compare ); //函数指针//传参
    cout << "--------------------------------------\n";     
    Test<cmp> t; //默认构造 //不要加小括号!否则就成函数声明了 //Test<cmp> ( );//显式构造

    return 0;
}

  三、非const类对象重载 非const 调用操作符

#include <iostream>
using namespace  std;

class  revision_string{
    string s{"Hello"}; //
public:
    string& operator()(const string& s){//非const函数//可以修改对象
        return this->s = s;
    }
};    

template<typename T>     //模板类
struct Test{
    Test(T &t ){ // 非const引用 
        cout << "Test( T &t )\n";
        cout << t("world"); //非const对象,调用非const调用操作符
    }
};

int main () 
{
    revision_string rs;//非const类对象
    Test<revision_string> t(rs ); //构造对象,参数为非const类对象

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值