[英]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=8
、 n=3
和m=2
。
另一件事将void main()
更改为int main()
。 请参见main() 在 C 和 C++ 中应该返回什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.