一、成员函数模板

#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::innerClass<float> 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_cast<Ty>(value);
    }

  private:
    Ty m_value;
};

int main() {
    TestClass<double> t;
    t.show(20.5f);
    return 0;
}

重要注意事项:

1. 成员模板不能是虚函数

2. 在类外定义成员模板时,需要提供两个模板参数列表

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐