[Solved] Templates in C++ / reference


The problem is in foreach templated function:

  • first parameter can be a pointer to the array or it can just be static array array with undefined size
  • second parameter can be a function pointer or a reference to the function (which should accept constant element of same type as array elements by reference, as it will not be modified)
  • third parameter should be different type as array size is not necessarilly same type as array element type

Fixed ex03.hpp looks like this:

#ifndef __EX03_H_INCLUDED__
#define __EX03_H_INCLUDED__

#include <iostream>

// option 1
template<typename T1, typename T2>
void foreach(T1* arr, void (*fnc)(const T1&), T2 size) {
    for (T2 i = 0; i < size; i++) {
        (*fnc)(arr[i]);
    }
}

// option 2
template<typename T1, typename T2>
void foreach(T1 arr[], void (&fnc)(const T1&), T2 size) {
    for (T2 i = 0; i < size; i++) {
        (*fnc)(arr[i]);
    }
}

template<typename T1>
void print(const T1& element) {
    std::cout << element << std::endl;
}

#endif /* !__EX03_H__ */

And the main.cpp:

#include "ex03.hpp"

#include <string>

int main() {
    const size_t tab1Size = 4;
    int tab1[tab1Size] = { 11, 3, 89, 42 };

    foreach(tab1, print, tab1Size);

    const size_t tab2Size = 5;
    std::string tab2[tab2Size] = { "j’", "aime", "les", "templates", "!" };
    foreach(tab2, print, tab2Size);

    return 0;
}

But i agree as others said before, you should first learn the basics of c++, so it can be easier to understand more complicated stuff.

1

solved Templates in C++ / reference