为什么clang将字符串文字作为指针而不是数组?

xml*_*lmx 7 c++ standards overloading string-literals

#include <iostream>
using namespace std;

void f(const char* arg)
{
    cout << "arg is a pointer" << endl;
}

template<size_t N>
void f(const char (&arg)[N])
{
    cout << "arg is an array." << endl;
}

int main()
{
    f("");
}
Run Code Online (Sandbox Code Playgroud)

我的编译器是clang 3.8.

输出是:

arg是一个指针

但是,根据cppreference.com,

未加前缀的字符串文字的类型是const char [].

为什么重载决策的行为不符合预期?

mol*_*ilo 8

它表现得像预期的那样,你只需要调整你的期望;-)

const char[1]并且const char (&)[1]是不同的类型.

转换为const char*(数组到指针转换)和const (&char)[1](标识转换)都被认为是完全匹配,但非模板是比模板更好的匹配.

如果编写非模板大小特定的重载,

void f(const char (&arg)[1])
Run Code Online (Sandbox Code Playgroud)

你会得到一个错误,函数调用是不明确的.

  • 太慢了.:(作为参考,相关的标准见于N4141的表12 (2认同)