Candidate template ignored: could not match 'const type-parameter-0-0 *' against 'char'

14,370

Solution 1

void array_print(const T * array[], int size);

Request a pointer to an array. When the compiler looks at how the function is called it sees a which is an array not a pointer to an array. The types do not match so the template deduction fails. To fix this drop the * from the function so you have

void array_print(const T array[], int size);

Solution 2

You can make function deduce array size from its argument:

template <typename T, std::size_t size>
void array_print(T(&array)[size]) {
    int last = size - 1;
    for (int i = 0; i < last; i++) {
        std::cout << array[i] << " ";
    }
    std::cout << array[last] << std::endl;
}

int main()
{
    char a[5] = {"ASFD"};
    array_print(a);
}

also the next problem you will encounter after fixing compilation error, is linker error. As πάντα ῥεῖ said in comments, you need to move your function definition to header file.

Share:
14,370
Volodymyr Samoilenko
Author by

Volodymyr Samoilenko

Updated on June 12, 2022

Comments

  • Volodymyr Samoilenko
    Volodymyr Samoilenko almost 2 years

    I want to make my own library and I have some problems with template function's.

    main.cpp

    #include <iostream>
    #include "SMKLibrary.h"
    
    int main() {
        char a[5] = {"ASFD"};
    
        array_print(a,5);
    
        return 0;
    }
    

    SMKLibrary.h

    #ifndef SMKLIBRARY_H
    #define SMKLIBRARY_H
    
    #include <iostream>
    
    template <typename T>
    void array_print(const T * array[], int size);
    
    #endif
    

    SMKLibrary.cpp

    #include "SMKLibrary.h"
    
    template <typename T>
    void array_print(const T * array[], int size) {
        int last = size - 1;
        for (int i = 0; i < last; i++) {
            std::cout << array[i] << " ";
        }
        std::cout << array[last] << std::endl;
    }
    

    Can someone explain to me why I have this error?