1. 程式人生 > >非類型模板參數

非類型模板參數

boa ole fine wid getch private size default initial

非類型的參數是“普通的”參數,eg:指針,int,然而非類型的模板參數只能是整數類型(int , char , long long int ...),和枚舉類型,引用和指針

在頭文件裏:

#ifndef _GAMEBOARD_H
#define _GAMEBOARD_H
#include <iostream>
#include <vector>
template<typename T , size_t WIDTH , size_t HEIGHT>
class GameBoard
{
    public:
        GameBoard();
//        GameBoard(const T& src);    
//復制構造函數 // GameBoard(size_t inWidth,size_t inHeight); virtual ~GameBoard(); public: void setElemAt(size_t x,size_t y,const T& inElem); const T& getElem(size_t x,size_t y); size_t getWidth(){return WIDTH;} size_t getHeight(){return HEIGHT;}
static const size_t mDefaultWidth = 10; static const size_t mDefaultHeight = 10; private: //size_t mWidth,mHeight; // void copyFrom(const T& src); // void initialContainer(); T mCells[WIDTH][HEIGHT]; }; #endif //_GAMEBOARD_H

在源文件裏:

#include "
GameBoard.h" template<typename T , size_t WIDTH , size_t HEIGHT> GameBoard<T,WIDTH,HEIGHT>::GameBoard() :mCells() { //initialContainer(); } template<typename T , size_t WIDTH , size_t HEIGHT> GameBoard<T,WIDTH,HEIGHT>::~GameBoard() { } template<typename T , size_t WIDTH , size_t HEIGHT> void GameBoard<T,WIDTH,HEIGHT>::setElemAt(size_t x,size_t y,const T& inElem) { mCells[x][y] = inElem; } template<typename T , size_t WIDTH , size_t HEIGHT> const T& GameBoard<T,WIDTH,HEIGHT>::getElem(size_t x,size_t y) { return mCells[x][y]; }

在main函數裏:

#include <iostream>
#include <initializer_list>
#include "GameBoard.h"
#include "GameBoard.cpp"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

constexpr size_t constexprHeight(){return 10;}
int main(int argc, char** argv) 
{GameBoard<int,10,10> myGameBoard;
    GameBoard<int , 10, 10>myAnotherGameBoard;
    myGameBoard.setElemAt(2,3,12);
    myAnotherGameBoard = myGameBoard;
    std::cout << myAnotherGameBoard.getElem(2,3) << std::endl;
    
    int height = 10;
    const int constHeight = 10;
    
    //GameBoard<int,10,height> myGameBoard1;    //error
    GameBoard<int,10,constHeight> myGameBoard1;    //work
    GameBoard<int,10,constexprHeight()> myGameBoard2;//work
    return 0;
}

可以看出不能通過非常量的整數來指定高度和寬度,但是可以通過const,constexpr來表示;

非類型模板參數