关于C++中的模板类型参数
我在这里浏览了一些问题,发现一些示例代码传递了(看起来像)一个转换为 void 类型的整数作为模板化对象的类型参数。这是我的意思的一个例子:
SomeRandomObject<void(int)> Object;
如果有人能够解释代码的“void(int)”部分及其作用,我将不胜感激。
I've been browsing through some of the questions here and I found some sample code that passed (what looks like) an integer casted as type void as the type parameter for a templated object. Here's an example of what I mean:
SomeRandomObject<void(int)> Object;
I would appreciate it if someone could explain the "void(int)" part of the code and what it does.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该类型是“采用
int
并返回void
的函数”。That type is "function that takes an
int
and returnsvoid
".该类型是函数类型。您可能不太熟悉它,因为到目前为止它仅用于指针类型:
函数本身确实有类型,但由于您无法声明该类型的变量或对该类型的引用,因此您通常唯一使用的就是指针,它们在最后一行以熟悉的语法声明。对于任何函数
int foo(void);
,foo
和&foo
都被解释为指针,因此“原始”函数类型不需要ft
。然而,随着围绕
std::function
、std::bind
和 lambda 的新模板魔法,现在在模板参数中看到裸函数类型变得更加常见。The type is a function type. You may not be so familiar with it, because until now it has only been used in pointer types:
Functions themselves do have types, but since you cannot declare variables of that type or references to it, the only thing you would typically use are pointers, which are declared in the familiar syntax on the last line. For any function
int foo(void);
, bothfoo
and&foo
are interpreted as the pointer, so the "raw" function typeft
isn't needed.However, with the new template magic surrounding
std::function
,std::bind
and lambdas, it is now a much more common thing to see naked function types in template parameters.