我正在尝试熟悉 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/