简体   繁体   English

创建一个C ++模板函数,该函数将返回特定大小的std :: array

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

I am creating a function titled linspase with C++17 with the following input structure linspace(double upper, double lower, int size) . 我正在使用以下输入结构linspace(double upper, double lower, int size)使用C ++ 17创建一个名为linspase的函数。 The function should create size evenly spaced numbers between lower and upper . 函数应该在lowerupper之间创建size均等的数字。 Programming this function is easy; 对该功能进行编程很容易; however, I want it to create an std::array<double, size> where the function will determine the array size from the function call and pass back the data type std::array<double, size> . 但是,我希望它创建一个std::array<double, size> ,该函数将从函数调用中确定数组大小,并将数据类型传递回std::array<double, size> I know templates are the only way to do this, but I am not sure how to build the template. 我知道模板是执行此操作的唯一方法,但是我不确定如何构建模板。 In a general pseudo code I think it looks something like this. 在一般的伪代码中,我认为它看起来像这样。

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
}

However, I know this template declaration is not right and I am not sure what it is supposed to look like. 但是,我知道此模板声明不正确,并且我不确定它的外观。 To be clear, I want it to return an std:;array of a specific size, not an std::vector . 明确地说,我希望它返回特定大小的std:;array ,而不是std::vector

If you (correctly) pass the array size as a template parameter, you don't need it as one of the function arguments, so: 如果(正确)将数组大小作为模板参数传递,则不需要将其作为函数参数之一,因此:

template <size_t size>
auto linspace(double lower, double upper) -> std::array<int, size>
{
    std::array<int, size> arr{};
    //populate the array ...
    return arr;
}

Since you're using c++14, you can get rid of the return value altogether, and have a prototype like: 由于您使用的是c ++ 14,因此可以完全摆脱返回值,并拥有一个类似以下的原型:

template <size_t size>
auto linspace(double lower, double upper)

Then you can use it like this: 然后,您可以像这样使用它:

auto arr = linspace<1>(0, 1);

for(auto a : arr)
{
    std::cout << a << std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM