问题描述
限时送ChatGPT账号..调用模板函数时,可以省略函数名后的类型吗?
When calling a template function, is it ok to omit the type after the function name?
以函数为例
template
template
<typename T
> void f(T var){...};
可以这样简单地称呼它吗:
Is it ok to simply call it like this:
int x = 5;
f(x);
int x = 5;
f(x);
还是我必须包含类型?
int x = 5;
f
int x = 5;
f<int
>(x);
推荐答案
只要编译器可以从函数参数中推断出模板参数,就可以将它们排除在外.这也是一种很好的做法,因为它会使您的代码更易于阅读.
Whenever the compiler can infer template arguments from the function arguments, it is okay to leave them out. This is also good practice, as it will make your code easier to read.
另外,你只能留下结尾的模板参数,而不是开头或中间:
Also, you can only leave template arguments of the end, not the beginning or middle:
template<typename T, typename U> void f(T t) {}
template<typename T, typename U> void g(U u) {}
int main() {
f<int>(5); // NOT LEGAL
f<int, int>(5); // LEGAL
g<int>(5); // LEGAL
g<int, int>(5); // LEGAL
return 0;
}
这篇关于在 C++ 模板中省略参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论