传递给std::function template的template参数究竟代表什么

What exactly is represented by the template parameter passed to std::function template?

本文关键字:template 究竟 什么 参数 std function      更新时间:2023-10-16

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

实时