字符串文字的模板参数推导

fre*_*low 6 c++ arrays templates pointers c++11

template<typename T>
void print_size(const T& x)
{
    std::cout << sizeof(x) << '\n';
}

int main()
{
    print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
    // prints 115
}
Run Code Online (Sandbox Code Playgroud)

这在最近的g ++编译器上打印115.显然,T推断是一个数组(而不是一个指针).标准是否保证了这种行为?我有点惊讶,因为以下代码打印指针的大小,我认为auto行为与模板参数推导完全一样?

int main()
{
    auto x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
    print_size(x);
    // prints 4
}
Run Code Online (Sandbox Code Playgroud)

R. *_*des 8

auto行为完全1,如模板参数推导.完全一样T!

比较一下:

template<typename T>
void print_size(T x)
{
    std::cout << sizeof(x) << '\n';
}

int main()
{
    print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
    // prints 4
    auto x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
    print_size(x);
    // prints 4
}
Run Code Online (Sandbox Code Playgroud)

有了这个:

template<typename T>
void print_size(const T& x)
{
    std::cout << sizeof(x) << '\n';
}

int main()
{
    print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
    // prints 115
    const auto& x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
    print_size(x);
    // prints 115
}
Run Code Online (Sandbox Code Playgroud)

1不完全,但这不是一个极端的案例.