Search code examples
c++templatestypedeftypename

C++ Template using typename and passing typedef to function


I am using template in this manner.

#define MAX_CARS 999
typedef char plate[20];

template <typename T>
int insert_ord (T V[], int ll, int const LF, T e);

It works but when I pass a typedef as arguments it says: No matching function for call to "insert_ord".

This is the main.

int main (void)
{
    plate targhe[MAX_CARS];        
    int ll = 0;

    plate targa;
    cin >> targa;

    ll = insert_ord(targhe, ll, MAX_CARS, targa);

    cout << endl;
    system("pause");
    return 0;
}

Solution

  • template <typename T>
    int insert_ord (T V[], int ll, int const LF, T e);
    

    The function-template above will not work for arguments of type:

    (int[999][20], int, int, int[20])
    

    The first parameter of your insert_ord function is a 2D array of plate, while the last is of type plate which is a 1D array. You should declare the function-template like:

    template <typename T, int sizeOuter, int sizeInner>
    int insert_ord (T (&v)[sizeInner][sizeOuter], int ll, int const LF, T (&e)[sizeOuter]);
    

    See it Live On Coliru


    However, a few nitpicks with your code. you don't need that void in int main(). And prefer constexpr over #define if possible. Most importantly, use std::array<T, N> or consider wrapping your data structure in a class or struct