菜鸟笔记
提升您的技术认知

C++ 一个类的成员函数可以是模板函数么?

1,一个普通类的一个成员函数可以成为模板成员函数么?

答案是可以的,实例如下

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

class PrintIt {
public:
    PrintIt(ostream &os) :_os(os) {
    }

    template <typename elemType>
    void print(const elemType& elem, char delimiter = '\n') {
        _os << elem << delimiter;
    }
private:
    ostream & _os;
};

int main()
{
    PrintIt to_standard_out(cout);
    to_standard_out.print("hello");
    to_standard_out.print(1024);

    string my_string("this is a string!");
    to_standard_out.print(my_string);


    getchar();
    return 0;
}

//输出
hello
1024
this is a string!

2,一个模板类的一个成员函数可以是一个别的类型的模板成员函数么?

答案也是可以的,实例如下

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

template<typename OutStream>
class PrintIt {
public:
    PrintIt(OutStream &os) :_os(os) {
    }

    // 虽然_os可以为各种类型,但这里只能为ostream
    template <typename elemType>
    void print(const elemType& elem, char delimiter = '\n') {
        _os << elem << delimiter;
    }
private:
    OutStream & _os;
};

int main()
{
    PrintIt<ostream> to_standard_out(cout);
    to_standard_out.print("hello");
    to_standard_out.print(1024);

    string my_string("this is a string!");
    to_standard_out.print(my_string);

    getchar();
    return 0;
}
//输出
hello
1024
this is a string!