如何调用以不同类模板作为参数列表的函数模板
how to call a function template that takes different class templates as parameters list
我需要制作一个模板函数,它需要两个不同大小的std::array
,但我不知道如何从main
函数调用它:
// write a function to combine two sorted arrays and keep the resulting array sorted
#include<iostream>
#include<array>
using namespace std;
template <class T, size_t size>
template <class T, size_t size_1>
template <class T, size_t size_2>
array<T, size> combine(array<T, size_1> a, array<T, size_2> b)
{
int i, j, k;
i = j = k = 0;
array<T, size> c;
while (i < size_1 && k < size_2) {
if (a[i] < b[k]) {
c[j] = a[i];
j++;
i++;
} else {
c[j] = b[k];
j++;
k++;
}
}
if (i < size_1) {
for (int q = j; q < size_1; q++)
c[j] = a[q];
} else {
for (int e = k; e < size_2; q++)
c[j] = b[e];
}
return c;
}
int main()
{
std::array<int, 5> a = { 2, 5, 15, 18, 40 };
std::array<int, 6> b = { 1, 4, 8, 10, 12, 20 };
std::array<int, 11> c;
c = combine<int>(a, b);
for (int i = 0; i < c.size(); i++) {
cout << c[i];
}
return 0;
}
您要做的是传入两个大小不同的array
,并返回一个大小为两个大小之和的array
。
你可以这样声明你的函数:
template <typename T, std::size_t X, std::size_t Y>
std::array<T, X+Y> combine (std::array<T, X> a, std::array<T, Y> b)
{
//...
}
通过这种方式,模板函数参数推导将起作用。因此,可以避免使用显式模板参数来调用函数。
std::array<int, 5> a = { 2, 5, 15, 18, 40 };
std::array<int, 6> b = { 1, 4, 8, 10, 12, 20 };
auto c = combine(a, b);
相关文章:
- 概念中的cv限定符需要表达式参数列表
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- 错误 没有与参数列表匹配的重载函数"getline"实例
- std::vector 没有重载函数的实例与参数列表匹配
- 模板参数列表中的 false 在模板初始化期间计算为什么?
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- 构造函数/函数声明参数列表中的统一初始化
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何将类成员方法的参数列表自动填充写入可变参数?
- 带有整数的变量参数列表
- 转发变量参数列表以模拟 std::thread
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- C++-将具有引用的长参数列表重构为结构
- 缺少别名模板C++参数列表
- C++如果两个模板函数都与参数列表匹配,将调用哪个模板
- "extern"声明以及带有和不带参数列表的类模板实例的后续定义
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- 没有函数模板的实例与我不知道为什么的参数列表匹配
- 我可以使用宏自动构建参数列表吗?
- 类成员函数参数列表是否可以依赖于模板参数?