#include
#include
#include <string>
/*
templatestruct::type aligned_storage;
相当于一个内建的POD类型他的大小是Size他的对齐方式是Align
*/
template<class T, std::size_t N>
class static_vector
{
typename std::aligned_storage<sizeof(T), __alignof(T)>::type data[N];
std::size_t m_size = 0;
public:
//类似于vector的push_back,使用了变长模板参数
//和placement new
template
void emplace_back(Args&&... args)
{
if (m_size >= N)
throw std::bad_alloc{};
new(data + m_size) T(std::forward(args)...);
++m_size;
}
const T & operator[](std::size_t pos) const
{
const T * ret = reinterpret_cast<const T*>(data + pos);
return *ret;
}
~static_vector()
{
for (std::size_t pos = 0; pos pos)
reinterpret_cast(data + pos)->~T();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::cout <<__alignof(std::string) << std::endl;
static_vectorstring, 10> v1;
v1.emplace_back(5, '*');
v1.emplace_back(10, '*');
std::cout <0] <<'\n' <1] <<'\n';
return 0;
}