简体   繁体   中英

How to template an extern array?

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

global.cpp

#include <array>

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

I test arrays values in another code file like this:

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 beautiful except for one thing. I use this global array ( Arr ) in many other places.

That means if I need to change the number of variables (it have 3 in this example) I need to do the same over all code files... ...crazy...

I thought to use a template like this:

testarrays.cpp

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

...but it didn't compiled.

Someone have a tip to solve this problem?

A using statement could make this easier. Then you could use myArr in multiple places but only change the size once:

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

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

extern myArr arr;

Next put the definition of the global in a new file:

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

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

Finally use it in the other compilation units (.cpp files):

//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;
}

Just make header file with the forward declaration:

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

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

and include it where you need:

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

     TestingArrays(localarr);
     TestingArrays(arr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM