kubusabadi
kubusabadi

Reputation: 132

How to concatenate 2 Arrays based on templates?

I'm trying to get familiar with C++ templates. I need to write a template of function that concatenates 2 arrays:

template<typename T, int Size>
class Array
{
public:
    void push(int i, const T& t) { _elem[i] = t; }
private:
    T _elem[Size];
};

For example I have 2 arrays:

Array<int,3> a1;
Array<int,4> a2;

I don't know how to write this function, that will return

Array<int,7>. 

How should header of this function look like?

Upvotes: 2

Views: 874

Answers (2)

duselbaer
duselbaer

Reputation: 935

You should try it like this:

template<typename T, int A, int B>
Array<T, A+B> concatenate(Array<T, A> first, Array<T, B> second) 
{
    Array<T, A+B> result;
    for (int idx = 0; idx < A; ++idx) {
        result.push(idx, first[idx]);
    }
    for (int idx = 0; idx < B; ++idx) {
        result.push(idx+A, second[idx]);
    }
    return result;
}

Upvotes: 2

GManNickG
GManNickG

Reputation: 503865

You could do it like this, as a free-function outside the class:

template <typename T, int SizeA, int SizeB>
Array<T, SizeA + SizeB> join(const Array<T, SizeA>& first,
                                const Array<T, SizeB>& second)
{
    /* ... */
}

For what it's worth, you should probably use std::size_t from <cstddef> instead of int.

Upvotes: 1

Related Questions