c++ - 如何基于模板连接2个数组?

标签 c++ templates

我正在尝试熟悉 C++ 模板。我需要编写一个连接 2 个数组的函数模板:

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

例如我有 2 个数组:

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

我不知道如何编写这个函数,它会返回

Array<int,7>. 

这个函数的标题应该是什么样子?

最佳答案

你应该这样尝试:

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

关于c++ - 如何基于模板连接2个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6184716/

相关文章:

c++ - filebuf::openprot 的用途是什么,它有替代品吗?

c++ - 高级 C++ : Copy configuration (object) in a template template class's instance

c++ - 如何在另一个类模板中定义完全专用类的构造函数

templates - 如何在 Polymer 1.0 中对对象而不是数组使用 dom-repeat?

C++模板类继承

c++ - png++ 中的 undefined reference

c++ - 通过对象指针访问成员

c++ - 这个计算素数的程序能走多远?

c++ - 根据模板参数启用模板 Ctor

java - 指纹扫描仪