创建一个C 模板功能,该功能将返回特定大小的std ::数组

Create a C++ template function that will return an std::array of a specific size

本文关键字:功能 返回 数组 std 一个 创建      更新时间:2023-10-16

我正在创建一个名为linspase的函数,其中C 17具有以下输入结构linspace(double upper, double lower, int size)。该函数应在lowerupper之间创建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;
}