Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- // we define a class, that we will be constructing later
- class T
- {
- public:
- float _z;
- int _x, _y;
- T(float z) : _z{z} {} // constructor with only one, float-type parameter
- T(int x, int y) : _x{x}, _y{y} {} // constructor with two int parameters
- };
- // our array class
- class A
- {
- public:
- int _count = 0; // how many elements are in the array
- int _memory[256]; // memory for our objects - (256 * sizeof(T)) bytes wide
- void* operator[](int count) // returns the memory address of the count-th T element
- {
- return _memory + sizeof(T) * count; //begin of the memory + sizof(element) * element_count
- }
- template <typename... Args> // variadic template definition
- void emplace_back(Args&&... args) // variadic arguments
- {
- // construction of object T with args-constructor-arguments on specified memory location
- new (operator[](_count++)) T(std::forward<Args>(args)...);
- }
- };
- int main()
- {
- A arr; // array declaration
- arr.emplace_back(1, 3); // constructing first object T{1, 3} on address memory[0]
- arr.emplace_back(3.14f); // constructing second object T{3.14f} on address memory[sizeof(T) * 1]
- auto first = reinterpret_cast<T*>(&arr._memory[0]); // interpreting the memory as the object created (T) - first object
- auto second = reinterpret_cast<T*>(&arr._memory[sizeof(T)]); // ^^ second object
- printf("x0=%d\ny0=%d\n", first->_x, first->_y); // reading the ints from first object
- printf("z1=%f\n", second->_z); // reading z-value from the second object
- system("pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement