There is a class Array<T> .

Example of use:

 Array<string> a; a.add("test"); a.add("..."); //... 

How do I implement the initialization option

 Array<string> a = {"str1", "str2"}; 

?

  • one
    add an appropriate constructor accepting an initialization list (possibly starting from ++ 11) - ampawd

2 answers 2

Taken here http://www.bogotobogo.com/cplusplus/C11/C11_initializer_list.php

In general, you need to write something

 Array(const std::initializer_list<T> &v) { for (auto itm : v) { add(itm); } } 

(since you have templates there, you need to take this into account. But your code is not there, therefore there is no guarantee for compilation).

  • one
    auto itm or auto &itm or auto &&itm ? And generally, and it is impossible to shift to compile-time? - Qwertiy
  • initializer_list<T> must be passed by value, and certainly not by a constant link. - Abyx
  • @Qwertiy what to shift? premature optimization? It depends on what's inside. If inside a class a regular vector, then it is possible in one line, and if there is a super fancy assembly language? - KoVadim
  • Well, initializer_list, according to my ideas, is needed to write everything into curly brackets and it was already compiled as it should be in the memory without unnecessary calls. And this piece from the answer as a matter of fact simply takes some intermediate array and in shifts it shifts. Or am I misunderstanding something? - Qwertiy
  • I think you read about std :: move and how to initialize structures. compiler can be difficult to guess the whole internal structure of your class - KoVadim

You can do the same as the stl developers in std::array

 template<class T, int size> class Array{ public: T data[size]; //... }; Array<std::string, 10> arr = {"1", "2", "3"};