关于 C++ 的问题模板
假设如下模板定义(代码无意义):
template<class X, class Y>
bool FooBar(const Y& val) { return sizeof(X) + 4; }
我发现下面的调用代码是合法的:
float temp = 0.f;
FooBar<int>(temp);
正如你所看到的,第二个类型参数 Y
可以省略。编译器通过查看 temp
的参数类型来推断 Y
的类型。
C++ 模板的什么规则或规范允许这样做?看到它我很惊讶。
Suppose the following template definition (the code is meaningless):
template<class X, class Y>
bool FooBar(const Y& val) { return sizeof(X) + 4; }
I have found that following calling code was legal:
float temp = 0.f;
FooBar<int>(temp);
As you can see, the second type parameter Y
can be omitted. A compiler infers the type of Y
by looking the argument type of temp
.
What rule or specification of C++ template allows this? I was pretty surprised to see it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是模板实参推导;这与使用
X
作为FooBar
的值参数的类型并在完全不使用任何模板参数的情况下调用它是一样的。有一个包含更多详细信息的文档 IBM 的编译器站点。That is template argument deduction; it is the same as if you used
X
as the type of a value parameter ofFooBar
and called it without any template arguments at all. There is a document with more details at IBM's compiler site.14.7.1 第 2 段:
正如 Jeremiah 指出的,参数演绎是你真正要问的:
14.8.2:
该过程在那里详细描述。
来源:ISO/IEC 14882:1998(E)
14.7.1 Paragraph 2:
As Jeremiah points out, argument deduction is what you're really asking about:
14.8.2:
The process is described in detail there.
Source: ISO/IEC 14882:1998(E)
这称为“隐式模板实例化”。参见标准第 14.7.1 节。我要指出的是,这在函数模板中非常常用。
This is called 'implicit template instantiation'. See the standard, section 14.7.1. I would note that this is very commonly used for function templates.
您不一定需要指定每个类型参数。本质上,编译器根据传入参数的类型计算出 Y,并且您在声明中指定了 X。这只是 Java 和 C++ 之间的另一个区别。
You aren't necessarily required to specify each type parameter. Essentially, the compiler figures out Y from the type of the parameter passed in, and you specified X in your declaration. Just another difference between Java and C++.