Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 for loop in a Template Function

Tags:

c++

c++11

I am trying to write a function which would Print Data on the console. The function is to be templated as it should accept different types of Data.

The code is as shown below:

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;
}

I get an error that variable Data is undeclared in the templated function 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 *'  

Any help would be appreciated. Thanks

like image 405
Barry Avatar asked Apr 08 '26 05:04

Barry


1 Answers

Assuming you have included the iostream header file and the using namespace std; directive. Then your problems are:

  1. You should not use DataType *. Your code makes X a pointer, which is different from array. Use DataType const& or DataType&& instead.
  2. You have to include the iterator header file which provides the begin and end function for C-style array.

The following code works for me.

#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;
}

As commented by Igor Tandetnik, you may use template<struct DataType, size_t N> if you want to refer the size of the array.

Update:

  1. With template<struct DataType> and DataType *X, DataType is deduced as int and double, and X is a pointer which is not a container.
  2. With template<struct DataType, size_t N> and DataType (&X)[N], DataType is deduced as int and double, and X is an array which can be used with range-based for loop.
  3. With template<struct DataType> and DataType&& X or DataType const& X, DataType is deduced as int[7] or double[5], and X is an array as well.
like image 182
cqdjyy01234 Avatar answered Apr 09 '26 18:04

cqdjyy01234