MyArray.h
#pragma once
template <typename T, size_t S>
class MyArray
{
public:
constexpr int Size() const { return S; }//constexpr:can be evaluated at compile time.
T& operator[](size_t index)
{
#define MYDEBUGMODE 1
#ifdef MYDEBUGMODE
// a fake size check for debug mode.
if (!(index < S))
{
__debugbreak();
}
return m_Data[index];
#else
return m_Data[index];
#endif
}
const T& operator[](size_t index) const { return m_Data[index]; }
T* Data() { return m_Data; }
const T* Data() const { return m_Data; }
private:
T m_Data[S];
};
main.cpp
#include <iostream>
#include <array>
#include "inc/MyArray.h"
// how to write a fixed size stack allocated array data structures.
int main(void)
{
int stackArray[5];//compile time.
int arraySize = 5;
int* heapArray = new int[arraySize];//run time.
delete[] heapArray;
std::array<int, 10> stdArray = {1,2,3,4,5,6,7,8,9,10};
stdArray.size();
for (int i : stdArray)
{
std::cout << i << std::endl;
}
for (int i = 0; i < stdArray.size(); i++)
{
std::cout << stdArray[i] << std::endl;
}
// testing MyArray.
MyArray<int, 5> intData;
MyArray<std::string, 2> strData;
static_assert:an assert can actually evaluated at compile time.
//static_assert(data.Size() < 10, "Size is too large!");
data.Size() can be evaluated during compile time.
//MyArray<std::string, data.Size()> newData;
//const auto& intDataReference = data;
memset(intData.Data(), 0, intData.Size() * sizeof(int));//memset(&intData[0], 0, intData.Size() * sizeof(int));
strData[0] = "Cherno";
strData[1] = "C++";
for (size_t i = 0; i < strData.Size(); i++)
{
std::cout << strData[i] << std::endl;
}
//for (auto& element : strData )//how to deal with iterators is another video.
{
}
std::cin.get();
}
版权声明:本文为AlexiaDong原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。