Array of template type

I am working with dynamically allocated arrays that are template type.

I know it is a common practice to set declared arrays to 0, but since the type of the array can be a char or string then I thought about setting it to NULL. Would this work?

1
2
3
for(int i = 0; i < maxSize; i++){
  array[i] = NULL;  // ???
}


you can use the empty braced initializer in both cases but std::string still poses differences vis-a-vis other POD such as std::getline() vs std::cin. So it might make sense to specialize the template function for std::string:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# include <iostream>
# include <string>

template <typename T>
void dynamicArray()
{
    size_t S{};
    std::cout << "enter array size: \n";
    std::cin >> S;
    T* newArray = new T[S]{};
    for (size_t i = 0; i <S; ++i)
    {
        std::cout << "Enter array element " << i << "\n";
        std::cin >> newArray[i];
    }
    for (size_t i = 0; i < S; ++i)
    {
        std::cout << newArray[i] << "\n";
    }
    delete [] newArray;
}

template<> void dynamicArray<std::string>()
{
    size_t S{};
    std::cout << "enter array size: \n";
    std::cin >> S;
    std::cin.ignore();
    std::string* newArray = new std::string[S]{};
    for (size_t i = 0; i <S; ++i)
    {
        std::cout << "Enter array element " << i << "\n";
        getline(std::cin, newArray[i]);
    }
    for (size_t i = 0; i < S; ++i)
    {
        std::cout << newArray[i] << "\n";
    }
    delete [] newArray;
}

int main()
{
  dynamicArray<char>();
  dynamicArray<std::string>();
  dynamicArray<int>();
}
Topic archived. No new replies allowed.