Zwettekop
Zwettekop

Reputation: 93

How to give an array of templates as a parameter in a function?

I was studying for my C++ exam and noticed that my answer differs from the solution. The question was to write a method that gives the biggest double or string (by size) from an array with templates. I know that by passing the array as a parameter you give a pointer to the first index. I'm really confused on where I should write the "const" to signify that the array is not being altered though. Also the code contains 2 dutch words, "grootste" means "biggest", and "grootte" just means "size". PS: max= maximum

this is my solution:

#include <iostream>
using namespace std; 

template <typename T>
T grootste(T const [],int);
double grootte(double);

int grootte(const string&);


int main(){
    double getallen[5] = {5.5,7.7,2.2,9.8,9.9};
    string woorden[3] = {"geloof","hoop","de liefde"};

    cout << "Biggest number " << grootste(getallen,5) << "." << endl;
    cout << "Longest of 3 strings " << grootste(woorden,3) << "." << 
    endl;
    return 0;
    }

int grootte(const string &a){
    return a.size();
}
double grootte(double d){
    return d;
}

template <typename T>
T grootste (T const arr[], int lengte){
    T max=arr[0];
    for(int i=1;i<lengte;i++){
        if(grootte(arr[i])>grootte(max)){
            max = arr[i];
        }
    }
    return max;
}

this is the solution my course gives me, there was no main included and the other methods were the same. I wrote the solution again but now it's a literal copy from the pdf the students recieved. I'm sorry for the spacing, i have no idea why it does that.

template < class T >
T grootste ( const T * array , int lengte ){
    T gr = array [0];
    for ( int i =1; i < lengte ; i ++) {
        if ( grootte ( gr ) < grootte ( array [i ]) ){
            gr = array [i ];
        }
    }
return gr ;
}

Upvotes: 1

Views: 92

Answers (2)

balki
balki

Reputation: 27684

I always get confused when types get complex. Use a typedef/using statement to make it clear what you mean exactly.

using intptr = int*; //pointer to int

void foo(const intptr arr ) {  // a const pointer to int
    arr[0] = 32;
    // arr = nullptr; //This will fail
}

using cint = const int; 

void bar(cint* arr){  // pointer to const int
    //arr[0] = 42; //This will fail
    arr = nullptr;
}

template<class T>
struct Types {
    using Tptr = T*;
    using ConstT = const T;
};

template<class T>
T grootste(typename Types<T>::constT* arr, int length) { //pointer to const T, i.e Ts in the array cannot change
    //...
}

Upvotes: 0

molbdnilo
molbdnilo

Reputation: 66459

These parameters are all equivalent:

const T p[]
T const p[]
const T *p
T const *p

Which one to choose is a matter of taste and convention.

Upvotes: 1

Related Questions