模板函数中的指针

模板函数中的指针

本文介绍了为什么数组衰减到模板函数中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么数组会衰减为模板函数中的指针.

I don't understand why the array decays to a pointer in a template function.

如果您查看以下代码:当参数被强制为引用(函数 f1)时,它不会衰减.在另一个函数 f 中,它衰减.为什么函数 f 中的 T 类型不是 const char (buff&)[3] 而是 const char*(如果我理解正确的话)?

If you look at the following code: When the parameter is forced to be a reference (function f1) it does not decay. In the other function f it decays. Why is the type of T in function f not const char (buff&)[3] but rather const char* (if I understand it correctly)?

#include <iostream>

template <class T>
void f(T buff) {
    std::cout << "f:buff size:" << sizeof(buff) << std::endl;       //prints 4
}

template <class T>
void f1(T& buff) {
    std::cout << "f:buff size:" << sizeof(buff) << std::endl;       //prints 3
}

int main(int argc, char *argv[]) {
    const char buff[3] = {0,0,0};
    std::cout << "buff size:" << sizeof(buff) << std::endl;         //prints 3
    f(buff);
    f1(buff);
    return 0;
}

推荐答案

因为数组不能作为函数参数按值传递.
当您按值传递它们时,它们会衰减为指针.

Because arrays can not be passed by value as a function parameter.
When you pass them by value they decay into a pointer.

在这个函数中:

template <class T>
void f(T buff) {

T 不能是 char (&buff)[3] 因为这是一个参考.编译器会尝试 char (buff)[3] 按值传递,但这是不允许的.因此,为了使其工作,数组衰减为指针.

T can not be char (&buff)[3] as this is a reference. The compiler would have tried char (buff)[3] to pass by value but that is not allowed. So to make it work arrays decay to pointers.

您的第二个函数有效,因为这里的数组是通过引用传递的:

Your second function works because here the array is passed by reference:

template <class T>
void f1(T& buff) {

// Here T& => char (&buff)[3]

这篇关于为什么数组衰减到模板函数中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:15