C 模板用法:更改可变位置导致编译误差



我有一个这样的简单程序:

$ cat testcompile.cpp

    #include<stdio.h>
    int fd[2];
    template<int fd[]>
    void f(){printf("fdn");}
    int main(){
        f<fd>();
        return 0;
    }

编译并运行它,没问题,它只是打印" FD"。但是,如果我将fd [2]的位置更改为主函数,那么它将无法编译:

    #include<stdio.h>
    template<int fd[]>
    void f(){printf("fdn");}
    int main(){
        int fd[2];
        f<fd>();
        return 0;
    }

clang报告:

    testCompile.cpp:6:5: error: no matching function for call to 'f'
        f<fd>();
        ^~~~~
    testCompile.cpp:3:6: note: candidate template ignored: invalid
          explicitly-specified argument for template parameter 'fd'
    void f(){printf("fdn");}
         ^
    1 error generated.

此错误指示什么?有什么错吗?

首先,您需要记住模板是一件编译时间,所有这些都是由编译器处理的,并且在运行时间内什么也不做。

然后,您需要记住,最常见的局部变量处理是将它们放在堆栈上,并且在编译时可能不知道堆栈的位置。

现在,如果我们将所有内容放在一起,因为在编译时尚不知道堆栈分配的对象的位置,仅在运行时,您就无法使用模板使用的堆栈分配(即本地变量)。

它适用于全局变量,因为编译器可以知道对象的实际位置。

最新更新