pass reference to array in C++

前端 未结 3 1699
情话喂你
情话喂你 2020-12-08 06:51

Can any one help me understand the following code

#include 

void foo(const char * c)
{
   std::cout << \"const char *\" << std::         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 07:43

    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 
    
    template 
    void foo(const T* c)
    {
       std::cout << "const T*" << std::endl;
    }
    
    template 
    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.

提交回复
热议问题