gpt4 book ai didi

C++11 for 模板函数中的循环

转载 作者:太空狗 更新时间:2023-10-29 20:02:49 24 4
gpt4 key购买 nike

我正在尝试编写一个可以在控制台上打印数据的函数。该函数将被模板化,因为它应该接受不同类型的数据。

代码如下所示:

template<typename DataType>
void PrintData(DataType *X)
{
for (DataType Data : X)
{
cout << Data << "\t";
}
cout << endl;
}

int main()
{

int nArray[7] = { 7, 5, 4, 3, 9, 8, 6 };
double dArray[5] = { 4.3, 2.5, -0.9, 100.2, 3.0 };

PrintData(nArray);
PrintData(dArray);

system("pause");
return EXIT_SUCCESS;
}

我收到一个错误,指出模板函数 PrintData 中的变量数据未声明

error C2065: 'Data' : undeclared identifier 
error C3312: no callable 'begin' function found for type 'double *'
error C3312: no callable 'begin' function found for type 'int *'
error C3312: no callable 'end' function found for type 'double *'
error C3312: no callable 'end' function found for type 'int *'

如有任何帮助,我们将不胜感激。谢谢

最佳答案

假设您包含了 iostream头文件和 using namespace std;指示。那么你的问题是:

  1. 你不应该使用 DataType * .您的代码使 X指针,不同于数组。使用 DataType const&DataType&&相反。
  2. 您必须包含 iterator提供 begin 的头文件和 end C 风格数组的函数。

以下代码适合我。

#include <iostream>
#include <iterator>
using namespace std;

template<typename DataType>
void PrintData(DataType const& X)
{
for (auto Data : X)
{
cout << Data << "\t";
}
cout << endl;
}

int main()
{

int nArray[7] = { 7, 5, 4, 3, 9, 8, 6 };
double dArray[5] = { 4.3, 2.5, -0.9, 100.2, 3.0 };

PrintData(nArray);
PrintData(dArray);

return EXIT_SUCCESS;
}

正如 Igor Tandetnik 所说,您可以使用 template<struct DataType, size_t N>如果你想引用数组的大小。

更新:

  1. template<struct DataType>DataType *X , DataType推导为 intdouble , 和 X是一个不是容器的指针。
  2. template<struct DataType, size_t N>DataType (&X)[N] , DataType推导为 intdouble , 和 X是一个数组,可以与基于范围的 for 循环一起使用。
  3. template<struct DataType>DataType&& XDataType const& X , DataType推导为 int[7]double[5] , 和 X也是一个数组。

关于C++11 for 模板函数中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34940023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com