Function Overloading Based on Value vs. Const Reference

前端 未结 6 851
借酒劲吻你
借酒劲吻你 2020-11-27 06:21

Does declaring something like the following

void foo(int x)        { std::cout << \"foo(int)\"         << std::endl; }
void foo(const int &x)         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 06:54

    Not in C++. Functional languages such as Erlang and Haskell get closer by allowing you to specify function overloads based on parameter value, but most imperative languages including C++ require overloading based on method signature; that is, the number and type of each parameter and the type of the return value.

    The const keyword in the signature defines not the type of the parameter, but its mutability within the function; a "const" parameter will generate a compiler error if modified by the function or passed by reference to any function that doesn't also use const.

提交回复
热议问题