pass reference to array in C++

前端 未结 3 1698
情话喂你
情话喂你 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:32

    This appears to be different for various compilers.

    Mircosoft and Borland both use the const char* version, while GNU is giving the output you described.

    Here is a snippet from the C++ standard:

    14.8.2.1 Deducing template arguments from a function call [temp.deduct.call]

    Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below.

    If P is not a reference type:

    -- If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is used in place of A for type deduction; otherwise,

    -- If A is a function type, the pointer type produced by the function-to-pointer standard conversion (4.3) is used in place of A for type deduction; otherwise,

    -- If A is a cv-qualified type, the top level cv-qualifiers of A's type are ignored for type deduction.

    If P is a cv-qualified type, the top level cv-qualifiers of P's type are ignored for type deduction. If P is a reference type, the type referred to by P is used for type deduction

    The compiler will build an A list as follows:

    Argument:        t                 d
    A:          char const[34]      char[34]
    

    And parameter list P:

    Parameter:       c                 t
    P:            char const*       char const& t[N]
    

    By default the compiler should choose non-referenced parameters. GNU is dong it wrong the second time for some reason.

提交回复
热议问题