C++ 模版template

C++ Template

模版类的继承和组合提供了对象代码复用的方法

Inheritance and composition provide a way to reuse object code. The template feature in C++ provides
a way to reuse source code.

template语法(Template syntax)

template关键字告诉编译器,模版类可以操控一个或者多个类型不明确的类型,这时实际的类的代码将会被编译器所产生,这些不确定的类型将会被确定以便编译器可以构造特定的类来代替他。

The template keyword tells the compiler that the class definition that follows will manipulate one or more unspecified types. At the time the actual class code is generated from the template, those types must be specified so that the compiler can substitute them.

//
// Created by 王若璇 on 17/3/29.
//
#include 

using namespace std;
template<class T,int size=100>
class Array {
//    enum { size = 100 };
    T A[size];

public:
    T& operator[](int index);
    void foo(const T& x) const;
    int getSize() const;
};

template<class T,int size>
T& Array::operator[](int index) {

    return A[index];
}

template <class T,int size>
void Array::foo(const T &x) const {

}

template <class T ,int size>
int Array::getSize() const {
    return size;
}

int main() {
    Array<double > b;
    Array<float,10> fa;
    cout<" "<///:~

output:

100 10

以上是一个模版类的定义,注意在模版类中的成员函数non-inline definition,都必须遵循如下形式的定义:

template <class T>
returnType classNmae::functionName(parameters){ function body}
  • 模版的参数不仅仅是typename T,也可以使用c++ 内建的数据类型作为参数。

Reference

Thinking in c++ template

你可能感兴趣的:(C++进阶学习笔记)