c++ - 字符串文字的模板参数推导

标签 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
}

这在最近的 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
}

最佳答案

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
}

有了这个:

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
}

1 不完全是,但这不是极端情况之一。

关于c++ - 字符串文字的模板参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13308887/

相关文章:

c++ - 对如何初始化类成员感到困惑

java - 整数数组的除法和

arrays - 如何更改此数组以将物理体赋予每个单独的节点(位掩码)?

python - Django 模板迭代列表

c++ - 是否可以将模板派生的 C++ 类与 Qt 的 Q_OBJECT 混合使用?

c++ - 对是或否陈述的无效回答

c++ - 稳定级联阴影映射中的光 View 矩阵

c - 排序数组的前 n 个元素

c++ - 友元、模板、命名空间

c++ - const char * 和 const char (& p)[T_Size] 之间的最佳查找匹配