非类型的参数是“普通的”参数,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来表示;