在 C++ 模板中省略参数

编程入门 行业动态 更新时间:2024-10-11 21:27:12
本文介绍了在 C++ 模板中省略参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

调用模板函数时,可以省略函数名后的类型吗?

When calling a template function, is it ok to omit the type after the function name?

以函数为例

template> void f(T var){...};

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>(x);

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:关键词]

本文发布于:2023-05-01 06:12:57,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!