简体   繁体   English

编译器如何不使用size参数处理此模板化函数

[英]How does the compiler handle this templated function with no size parameter

In the code below, I have a function where a length parameter must be passed, like this: 在下面的代码中,我有一个必须传递长度参数的函数,如下所示:

int recv(char* buf, int len);

But a convenience is to write a helper function like this: 但是方便的是编写这样的辅助函数:

    template <size_t N>
    int recv(char(&array)[N]) {
        return recv(array, N);
    }

Which means you can pass an array and the compiler somehow 'knows' the size so you don't have to pass it. 这意味着您可以传递数组,并且编译器以某种方式“知道”大小,因此您不必传递它。

But when I have used templates before, I needed to pass the type, eg 但是当我以前使用模板时,我需要传递类型,例如

std::vector<int> myvec;

But how does that work? 但是,如何运作? Internally what is the compiler doing to resolve this? 在内部,编译器在做什么以解决此问题? What is the name of this feature? 此功能的名称是什么?

Please explain the syntax. 请解释语法。

#include <string.h>
#include <iostream>

class test_recv
{
public:
    test_recv() {
        strcpy(arr, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    }
    int recv(char* buf, int len) {
        int tmp = pos;
        while (len-- && pos < 26)
            *buf++ = arr[pos++];

        return pos - tmp;
    }
    template <size_t N>
    int recv(char(&array)[N]) {
        return recv(array, N);
    }

private:
    int pos = 0;
    char arr[26+1];
};


int main() {
    test_recv test;
    char buffer[10];
    int bytes;
    while ((bytes = test.recv(buffer, 10)) != 0) {
        for (int i = 0; i < bytes; ++i)
            std::cout << buffer[i];
    }

    std::cout << '\n';
    test_recv test2;
    char buffer2[10];
    while ((bytes = test2.recv(buffer2)) != 0) {
        for (int i = 0; i < bytes; ++i)
            std::cout << buffer2[i];
    }
}

This feature is called "template argument deduction" . 此功能称为“模板参数推导” See the link for more details. 请参阅链接查看更多细节。

Short version: If, in a call to a templated function, the template arguments (types, or in your case, array size) can be deduced from the arguments the function is called with (in your case, the actual array), you don't have to specify them explicitly. 简短版本:如果在调用模板函数时可以从调用函数的参数(在您的情况下为实际数组)中推导出模板参数(类型,在您的情况下为数组大小),则不要不必明确指定它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM