C++:使用模板参数作为模板函数中的默认参数

C++: Using a template parameter as a default argument in a template function

给出下面的代码片段:

template<int n, double m>
void function(int x=n){
 double y=m;
 int array[n];
 ….
}

void main () {
 function<1+2,2>(8);
}

编译函数时 x 是 3 还是 8(因为 n 只是默认参数)?

在您的示例中,n 为 3,x 为 8。实际参数值优先于默认值。

该代码有什么好处!!

模板非类型参数必须是结构类型(不能是双精度)。参见 https://en.cppreference.com/w/cpp/language/template_parameters#Non-type_template_parameter

因此,如果 double 更改为 int,则变量将为 x=8n=3m=2

另一件事将 void main() 更改为 int main()。参见 What should main() return in C and C++?