码迷,mamicode.com
首页 > 其他好文 > 详细

带有非类型参数的方法模板

时间:2019-02-08 10:26:39      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:idt   str   else   cells   min   span   name   ted   class   

在GameBoard.h文件里:

//
// Created by Administrator on 2019/2/6.
//

#ifndef GAMEBOARDTEMPLATE_GAMEBOARD_H
#define GAMEBOARDTEMPLATE_GAMEBOARD_H
#include<iostream>
#include <vector>

template<typename T , size_t WIDTH = 10 , size_t  HEIGHT = 10>
class GameBoard
{
public:
    GameBoard() : mCells(){}
    virtual ~GameBoard();

    template<typename E , size_t WIDTH1 , size_t HEIGHT1>
    GameBoard(const GameBoard<E,WIDTH1,HEIGHT1>& src);

    template<typename E , size_t WIDTH1 , size_t HEIGHT1>
    GameBoard<T,WIDTH,HEIGHT>& operator = (const GameBoard<E,WIDTH1,HEIGHT1>& rhs);

    void setElemtAt(size_t x,size_t y,const T& src);
    const T& getElemtAt(size_t x, size_t y);

public:
    size_t getWidth(){return mWidth;}
    size_t getHeight(){return mHeight;}



private:
    size_t mWidth,mHeight;
    template<typename E , size_t WIDTH1 , size_t HEIGHT1>
    void copyFrom(const GameBoard<E,WIDTH1,HEIGHT1>& src);
    T mCells[WIDTH][HEIGHT];
};



#endif //GAMEBOARDTEMPLATE_GAMEBOARD_H

在GameBoard.cpp里

#include "GameBoard.h"

template<typename T , size_t WIDTH , size_t  HEIGHT>
GameBoard<T,WIDTH,HEIGHT>::~GameBoard()
{

}

template<typename T , size_t WIDTH , size_t  HEIGHT>
template<typename E , size_t WIDTH1 , size_t HEIGHT1>
GameBoard<T,WIDTH,HEIGHT>::GameBoard(const GameBoard<E,WIDTH1,HEIGHT1>& src)
{
    copyFrom(src);
}

template<typename T , size_t WIDTH , size_t  HEIGHT>
template<typename E , size_t WIDTH1 , size_t HEIGHT1>
GameBoard<T,WIDTH,HEIGHT>& GameBoard<T,WIDTH,HEIGHT>::operator = (const GameBoard<E,WIDTH1,HEIGHT1>& rhs)
{
    copyFrom(rhs);
    return *this;
}
template<typename T , size_t WIDTH , size_t  HEIGHT>
void GameBoard<T,WIDTH,HEIGHT>::setElemtAt(size_t x,size_t y,const T& src)
{
    mCells[x][y] = src.getElemtAt(x,y);
}
template<typename T , size_t WIDTH , size_t  HEIGHT>
const T& GameBoard<T,WIDTH,HEIGHT>::getElemtAt(size_t x, size_t y)
{
    return mCells[x][y];
}

template<typename T , size_t WIDTH , size_t  HEIGHT>
template<typename E , size_t WIDTH1 , size_t HEIGHT1>
void GameBoard<T,WIDTH,HEIGHT>::copyFrom(const GameBoard<E,WIDTH1,HEIGHT1>& src)
{
    for(size_t i = 0;i < WIDTH;++i)
    {
        for(size_t j = 0;j < HEIGHT;++j)
        {
            if(i <= WIDTH1 && j <= HEIGHT1)
            {
                mCells[i][j] = src.mCells[i][j];
            }
            else
            {
                mCells[i][j] = 0;
            }
        }
    }
}

编写复制构造函数时,编译器不会自动生成默认的构造函数,因此必须手动添加一个默认的构造函数

带有非类型参数的方法模板

标签:idt   str   else   cells   min   span   name   ted   class   

原文地址:https://www.cnblogs.com/boost/p/10355896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!