创建一个C 模板功能,该功能将返回特定大小的std ::数组
Create a C++ template function that will return an std::array of a specific size
我正在创建一个名为linspase
的函数,其中C 17具有以下输入结构linspace(double upper, double lower, int size)
。该函数应在lower
和upper
之间创建size
均匀间隔的数字。编程此功能很容易;但是,我希望它创建一个std::array<double, size>
,其中函数将从函数调用确定数组大小并传递数据类型std::array<double, size>
。我知道模板是这样做的唯一方法,但是我不确定如何构建模板。在一般的伪代码中,我认为它看起来像这样。
template <typedef T, size_t size>
T linspace(double lower, double upper, int num)
{
/* ... Function meat goes here to create arr of size
num of evenly space numbers between lower and upper
*/
return arr
}
但是,我知道此模板声明不对,我不确定它应该是什么样的。要明确,我希望它返回特定尺寸的std:;array
,而不是std::vector
。
如果(正确(将数组大小作为模板参数传递,则不需要它作为函数参数之一,因此:
template <size_t size>
auto linspace(double lower, double upper) -> std::array<int, size>
{
std::array<int, size> arr{};
//populate the array ...
return arr;
}
由于您使用的是C 14,因此可以完全摆脱返回值,并具有类型:
template <size_t size>
auto linspace(double lower, double upper)
然后您可以这样使用:
auto arr = linspace<1>(0, 1);
for(auto a : arr)
{
std::cout << a << std::endl;
}
相关文章:
- 时钟功能返回零时差
- C++自动功能返回?
- 类型推论模板功能返回类型
- 从功能返回本地卡斯施说指针
- OPENCL-如何使辅助功能返回阵列并将内存的部分从恒定内存空间转移到私有
- C++ OPEN SSL 库 HMAC 功能返回值每次运行时都不相同
- 如果未存储由功能返回的指针,会发生什么
- 该功能返回空字符串
- C 制造功能返回数组交叉文件
- 当功能返回CSTRING时会发生什么
- 从功能返回将上下文更改为null
- 在模板中获取功能返回类型
- 从最大功能返回Stepanov注释
- 从功能返回时,向量的深拷贝行为
- 当功能返回时,Linux C 系统()调用崩溃
- STL模板功能返回一对
- 从C 中的功能返回时分割故障
- 提升侵入性unordered_set静态成员功能返回错误的尺寸类型
- 在功能返回之前,可以解锁Mutex会增加并发
- getProcAddress()为我的Hello World功能返回null