C++成员模板类

C++成员模板类 一、成员函数模板#include iostream #include string using namespace std; // 成员函数模板 class TestClass { public: template typename Ty void show(Ty value) { cout value: value endl; } }; int main() { TestClass t; t.show(10); t.show(10.5f); t.show(zhangsan); return 0; }二、成员类模板#include iostream #include string using namespace std; // 成员类模板 class TestClass { public: template typename Ty class innerClass { public: innerClass(Ty value) : m_data(value) {} void show() { cout m_data: m_data endl; } private: Ty m_data; }; }; int main() { TestClass::innerClassfloat test(20.5f); test.show(); return 0; }三、在类模板中的成员模板#include iostream #include string using namespace std; // 在类模板中的成员模板 template typename Ty class TestClass { public: template typename Ty2 void show(const Ty2 value) { m_value static_castTy(value); } private: Ty m_value; }; int main() { TestClassdouble t; t.show(20.5f); return 0; }重要注意事项1. 成员模板不能是虚函数2. 在类外定义成员模板时需要提供两个模板参数列表