//2020年05月12日 19时09分36秒
//professional C++ 4th edition p 260
#include
#include
#include
#include
#include
template
class Grid
{
public:
Grid() = default;
virtual ~Grid() = default;
// Explicitly default a copy constructor and copy assignment operator.
Grid(const Grid& src) = default;
Grid<T, WIDTH, HEIGHT>& operator=(const Grid& rhs) = default;
std::optional<T>& at(size_t x, size_t y);
const std::optional<T>& at(size_t x, size_t y) const;
size_t getHeight() const { return HEIGHT; }
size_t getWidth() const { return WIDTH; }
private:
void verifyCoordinate(size_t x, size_t y) const;
std::optional<T> mCells[WIDTH][HEIGHT];
};
template <typename T, size_t WIDTH, size_t HEIGHT>
void Grid<T, WIDTH, HEIGHT>::verifyCoordinate(size_t x, size_t y) const
{
if (x >= WIDTH || y >= HEIGHT) {
throw std::out_of_range("");
}
}
template <typename T, size_t WIDTH, size_t HEIGHT>
const std::optional& Grid<T, WIDTH, HEIGHT>::at(size_t x, size_t y) const
{
verifyCoordinate(x, y);
return mCells[x][y];
}
template <typename T, size_t WIDTH, size_t HEIGHT>
std::optional& Grid<T, WIDTH, HEIGHT>::at(size_t x, size_t y)
{
return const_cast<std::optional&>(std::as_const(*this).at(x, y));
}
constexpr size_t getHeight() //p261
{
return 10;
}
int main(){
// Grid<int, 10, 10> myGrid;
// Grid<int, 10, 10> anotherGrid;
//
// myGrid.at(2, 3) = 42;
// anotherGrid = myGrid;
// std::cout << anotherGrid.at(2, 3).value_or(0);
//
// // size_t height = 10;//错误:the value of ‘height’ is not usable in a constant expression
// const size_t height = 10;
// Grid<int, 10, height> testGrid;
// //p261
// Grid<double, 2, getHeight()> myDoubleGrid;
Grid <> myIntGrid;
Grid <int> myGrid;
Grid <int, 5> anotherGrid;
Grid <int, 5, 5> aFourthGrid;
Grid <double> myDoubleGrid;//p263
//Grid<int> 编写的函数接收类型为Grid<double>的对象, 就不能传入Grid<int> (int可以强制转换为double)
//不能将类型为Grid<int>的对象赋值给类型为Grid<double>的对象, 不能从Grid<int>构造Grid<double>
// myDoubleGrid = myGrid; //错误:
// Grid newDoubleGrid(myGrid); //错误:
}
#include
#include
#include
#include
#include