Why is `“literal”` encouraged to decay to `const char*` in C++ argument type match?

前端 未结 2 1300
半阙折子戏
半阙折子戏 2020-12-03 08:17

I\'m playing around with overloading operators in c++14, and I tried to match two types of arguments: any-old-const-char*, and a-string-literal.

That is, I\'m trying

2条回答
  •  失恋的感觉
    2020-12-03 08:31

    1. The overload taking a pointer is preffered because it is not a template according to

    13.3.3 Best viable function [over.match.best]

    ...

    Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then

    ...

    (1.7) F1 is not a function template specialization and F2 is a function template specialization

    1. actually non-template const char (&)[] does not seem to compile at all because it is a reference to a non-bound array. It is possible to pass a pointer like this const char [], but not array.

    2. this should fail at least for the same reason as (2)

    3. you can provide another template taking a reference to pointer:
    template< typename = void > void
    foo(char const * & text)
    {
        ::std::cout << "got ptr" << ::std::endl;
    }
    

    Note that providing another template taking a pointer won't work because both template specializations will be fine and we'll get ambiguous choice of overloaded functions.

提交回复
热议问题