You can declare and initialize regular arrays on the same line, like so:
int PowersOfTwo[] = {1, 2, 4, 8, 16, 32, 64, 128};
Is there a way to replicate this behavior in custom classes? So, for example:
MyClass<int> PowersOfTwo = {1, 2, 4, 8, 16, 32, 64, 128};
You can have a copy constructor take an array as its parameter, but you still have to declare the array on the previous line.
int InitializationArray[] = {1, 2, 4, 8, 16, 32, 64, 128};
MyClass<int> PowersOfTwo = InitializationArray;
You can implement your class in such a way that you can write this:
MyClass<int> array;
array = 1,2,3,4,5,6,7,8,9,10;//dont worry - all ints goes to the array!!!
Here is my implementation:
template <class T>
class MyClass
{
std::vector<T> items;
public:
MyClass & operator=(const T &item)
{
items.clear();
items.push_back(item);
return *this;
}
MyClass & operator,(const T &item)
{
items.push_back(item);
return *this;
}
size_t Size() const { return items.size(); }
T & operator[](size_t i) { return items[i]; }
const T & operator[](size_t i) const { return items[i]; }
};
int main() {
MyClass<int> array;
array = 1,2,3,4,5,6,7,8,9,10;
for (size_t i = 0 ; i < array.Size() ; i++ )
std::cout << array[i] << std::endl;
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
See online demo : http://www.ideone.com/CBPmj
Two similar solutions you can see here which I posted yesterday :
Template array initialization with a list of values
EDIT:
Similar tricks you can do to populate existing STL containers. For example, you can write this:
std::vector<int> v;
v+=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //push_back is called for each int!
All you need to overload ()
and ,
operator as:
template<typename T>
std::vector<T>& operator+=(std::vector<T> & v, const T & item)
{
v.push_back(item); return v;
}
template<typename T>
std::vector<T>& operator,(std::vector<T> & v, const T & item)
{
v.push_back(item); return v;
}
Working demo : http://ideone.com/0cIUD
AGAIN EDIT:
I'm having fun with C++ operator. Now this:
std::vector<int> v;
v << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //inserts all to the vector!
I think this looks better!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With