Created
October 24, 2015 14:55
-
-
Save xaizek/444e789c1fcfc850ad9b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstddef> | |
#include <iostream> | |
#include <new> | |
#include <utility> | |
template <typename T> | |
class Array | |
{ | |
public: | |
explicit Array(size_t size = 0, const T& value = T()) | |
: size_(size), | |
dat(reinterpret_cast<T*>(new char[sizeof(T[size])])) | |
{ | |
for (size_t i = 0; i < size; ++i) | |
{ | |
new (&dat[i]) T(value); | |
} | |
} | |
Array(const Array & a) | |
{ | |
size_=a.size(); | |
dat= new T [size_]; | |
for (size_t i = 0; i<size_; ++i) | |
dat[i]= a.dat[i]; | |
} | |
~Array() | |
{ | |
for (size_t i = 0; i<size_; ++i) | |
dat[i].~T(); | |
} | |
Array& operator=(const Array & a ) | |
{ | |
Array copy(a); | |
std::swap(*this, a); | |
return *this; | |
} | |
size_t size() const | |
{ | |
return size_; | |
} | |
T & operator[](size_t iter) | |
{ | |
return dat[iter]; | |
} | |
const T& operator[](size_t iter) const | |
{ | |
return dat[iter]; | |
} | |
private: | |
size_t size_; | |
T *dat; | |
}; | |
class Class | |
{ | |
public: | |
Class(int d) : d(d) {} | |
operator int() const { return d; } | |
private: | |
int d; | |
}; | |
int | |
main() | |
{ | |
Class c = 1; | |
Array<Class> a(10, c); | |
std::cout << a[5] << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment