How is an external array template?

I created a code file to save all my global variables, and one of them is an array like this:

global.cpp

#include <array>

array<string, 3> arr = {"value1", "value2","value3"};

I am testing the values ​​of arrays in another code file as follows:

testarrays.cpp

#include <iostream>
#include <array>

template <size_t N>
void TestingArrays(const array<string, N>& ArrT);

void ArrayTester()
{
     extern array<string,3> arr;

     array <string, 2> localarr = {"v1" ,"v2"};

     TestingArrays(localarr);
     TestingArrays(arr);
}

template <size_t N>
void TestingArrays(const array<string, N>& ArrT) 
{
     for (auto it = ArrT.cbegin(); it != ArrT.cend(); ++it)
     {
         cout << "Testing " << *it << endl;
     }
}

Everything is fine, except for one. I use this global array ( Arr) in many other places.

This means that if I need to change the number of variables (this one has 3 in this example), I need to do the same in all the code files ... crazy ...

I thought of using a template like this:

testarrays.cpp

...
     template <size_t N>
     extern array<string,N> arr;
...

... but it is not compiled.

Does anyone have a clue to solve this problem?

+4
source share
2 answers
Operator

A using . myArr , :

//header.h
#include <array>
#include <string>

using myArr = std::array<std::string, 3>;

extern myArr arr;

:

//myarr.cpp
#include "header.h"

myArr arr = {"value1", "value2","value3"};

, ( .cpp):

//main.cpp
#include "header.h"

#include <iostream>
#include <array>

template <size_t N>
void TestingArrays(const std::array<std::string, N>& ArrT);

void ArrayTester()
{
    //extern array<string, 3> arr; // global var doesn't need to be declared here if the header is included

    std::array<std::string, 2> localarr = {"v1" ,"v2"};

    TestingArrays(localarr);
    TestingArrays(arr);
}

template <size_t N>
void TestingArrays(const std::array<std::string, N>& ArrT)
{
    for(auto it = ArrT.cbegin(); it != ArrT.cend(); ++it)
    {
        std::cout << "Testing " << *it << std::endl;
    }
}

int main() {
    auto value = arr[1];
    ArrayTester();
    return 0;
}
+2

:

#pragma once
#include <array>
#include <string>

extern std::array<std::string, 3> arr;

, :

#include"arr.h"
...
void ArrayTester()
{
     array <string, 2> localarr = {"v1" ,"v2"};

     TestingArrays(localarr);
     TestingArrays(arr);
}
+1

Source: https://habr.com/ru/post/1657985/


All Articles