pass reference to array in C++

c++

Solution

Conversion of `const char[N]` to `const char*` is considered an "exact match" (to make literals easier, mainly), and between two exact matches a non-template function takes precedence.

You can use `enable_if` and `is_array` to force it to do what you want.

A messy way to force it might be:

#include <iostream>

template <typename T>
void foo(const T* c)
{
   std::cout << "const T*" << std::endl;
}

template <typename T, size_t N>
void foo(const T (&t) [N])
{
   std::cout << "array ref" << std::endl;
}

int main()
{
    const char t[34] = {'1'};
    foo(t);

    char d[34] = {'1'};
    foo(d);
}

/*
array ref
array ref
*/

I realise that the OP had `char` not some generic `T`, but nonetheless this demonstrates that the problem lay in one overload being a template and not the other.

Problem

Can any one help me understand the following code ``` #include <iostream> void foo(const char * c) { std::cout << "const char *" << std::endl; } template <size_t N> void foo(const char (&t) [N]) { std::cout << "array ref" << std::endl; std::cout << sizeof(t) << std::endl; } int main() { const char t[34] = {'1'}; foo(t); char d[34] = {'1'}; foo(d); } ``` The output is ``` const char * array ref 34 ``` Why does the first foo calls the `const char *` version ? How can I make it call the reference version ?

Original source

Related problems