C++模板用法:更改变量位置会导致编译错误

Tro*_*yvs 1 c++ linux templates compilation clang

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

$ cat testCompile.cpp

    #include<stdio.h>
    int fd[2];
    template<int fd[]>
    void f(){printf("fd\n");}
    int main(){
        f<fd>();
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

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

    #include<stdio.h>
    template<int fd[]>
    void f(){printf("fd\n");}
    int main(){
        int fd[2];
        f<fd>();
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

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("fd\n");}
         ^
    1 error generated.
Run Code Online (Sandbox Code Playgroud)

这个错误表示什么?哪里不对了?

Som*_*ude 8

首先,您需要记住模板是编译时的事情,它全部由编译器处理,并且在运行时没有任何操作.

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

现在,如果我们将它们放在一起,因为在编译时不知道堆栈分配对象的位置,仅在运行时,您不能使用与模板一起使用的堆栈分配(即局部变量).

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

  • @PremkumarU模板可以有非类型参数,以便在编译时传递值.在这个例子中,一个指针作为模板参数传递,因此在函数`fd`中不是一个类型,而是一个指向`int`的指针.就像它作为普通函数参数传递一样. (2认同)