Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char array template vs char const* function overload [duplicate]

I have looked at all the answers for the suggested related questions that stack overflow presented as I wrote this question, I have googled around, and I have looked at STL's video on overload resolution to try and figure out what makes the following code select the char const* overload over the template, but I can't figure it out.

#include <cstdio>

void foo( int i, char const* c_str_1, char const* c_str_2 )
{
   printf( "foo( int i, char const* c_str_1, char const* c_str_2 )\n" );
}

template< std::size_t N, std::size_t M >
void foo( int i, char const (&c_str_1)[N], char const (&c_str_2)[M] )
{
   printf( "foo( int i, char const (&c_str_1)[N], char const (&c_str_2)[M] )\n" );
}


int main( int argc, char* argv[] )
{
   char const* c_strg_1 = "This is a c style string.";
   foo( 1, c_strg_1, "bla" );
   foo( 1, "bla", "bla" );
   return 0;
}

It probably is something obvious I am missing, but the compiler always selects the char const* overload. I would have thought the template is an exact match and the other one needs a "decay"/"conversion".

Anyhow, thanks to anyone with insight into this.

like image 625
ghlecl Avatar asked Dec 06 '25 02:12

ghlecl


1 Answers

During the overload resolution usual functions are always preferred over function templates.

It means, that if there is an overload of foo which might accept appropriate arguments (even if the function template seems to be a better match), then the compiler will choose this overload.

In addition to that, for the first call:

foo( 1, c_strg_1, "bla" );

there is no way to instantiate a function template as c_strg_1 has a type of const char*.

like image 113
Edgar Rokjān Avatar answered Dec 08 '25 15:12

Edgar Rokjān



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!