传递给std::function template的template参数究竟代表什么
What exactly is represented by the template parameter passed to std::function template?
std::function
本身提供了一个很好的实用程序-它提供类型擦除,以便一般存储/提供对可调用文件的访问。它的灵活性很大:
#include <functional>
#include <iostream>
void printer() {
std::cout << "I print!";
}
int adder(int a, int b) {
return a + b;
}
int main() {
std::function<void()> fun1 = printer; // fun1() calls printer()
std::function<int(int, int)> fun2 = adder; // fun2(1, 2) calls adder(1, 2)
std::function<void()> fun3 = [](){}; // fun3() will do nothing - same for the lambda
std::function<int(int, int)> fun4 =
[](int a, int b) { return a + b; }; // fun4(1, 2) will yield the sum
}
老实说,一切都有道理。std::function<void()>
表示它是一个function
,当被调用时,它返回void
,不接受(()
(参数。std::function<int(int, int)>
也是如此——当被调用时,它返回一个int
,并需要两个int
作为其参数。
虽然直观,但我相信我对是显式模板参数这一点缺乏基本理解。void()
或int(int, int)
究竟是什么?它们不能是函数指针,因为当我这样做时:
int main() {
using type = void();
type x = printer;
}
我收到以下警告和错误:
main.cpp:15:10: warning: declaration of 'void x()' has 'extern' and is initialized type x = printer; ^ main.cpp:15:14: error: function 'void x()' is initialized like a variable type x = printer; ^~~~~~~
很明显,它看起来像一个变量——我希望它是一个变量。然而,如果我想要一个函数指针,我必须这样做:
using type = void(*)();
而不是:
using type = void();
省略*
的类型究竟是什么?当与例如std::function
一起使用时,直观的显式模板参数究竟代表了什么?
带省略*的类型究竟是什么?
想一想。类型"后跟"*
意味着"指向该类型的指针"。如果你没有用*
"跟随"一个类型,那么这个类型就意味着这个类型。所以,如果你有一个函数指针,那么它就是一个指向…函数类型的指针。
因此,像void()
这样的类型是函数类型。
函数类型不同于对象类型,但它们仍然是类型。因此,您可以使用它们玩C++允许的大多数基于类型的游戏。但由于它们不是对象类型,所以不能创建函数类型的对象。
void()
或int(int, int)
究竟是什么?
它们是函数类型。例如,如果您声明void foo()
,则foo
的类型为void()
:
#include <type_traits>
int main() {
static_assert(std::is_function_v<int(int, int)> &&
std::is_function_v<void()> &&
std::is_same_v<decltype(main), int()>);
}
实时
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 传递给std::function template的template参数究竟代表什么
- 在template中使用std::variant的template函数
- C++ template for QList
- C++ - 为什么这里需要'template'关键字?
- C++关于指针和使用函数将它们启动到堆的行为究竟是什么?
- 究竟如何工作范围?
- 使用"std::enable_if_t" "function template has already been defined"
- C++模板错误:"invalid explicitly-specified argument for template parameter"
- 当使用对象名称后带有 [] 的类对象时,您究竟会传入什么.C++
- C++ class template
- 在"template"和函数声明之间使用:template<typename trait> using tr = base_trait<trait> void fn(tr::t
- 为什么编译器说"candidate template ignored: couldn't infer template argument 'InputIterator'"?
- 哪种方式更快?究竟发生了什么,我们没有看到什么?
- 为什么在这种情况下我需要 .template
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 串行端口写入究竟如何从缓冲区实际写入数据?
- DrawShadow 中的 Elevation 究竟有什么作用?
- 究竟是什么设置了_WIN32或_WIN64预处理器?
- 我的重复检查代码中的错误究竟在哪里?