c++ - 传递给 std::function 模板的模板参数究竟代表什么?

标签 c++ function-pointers std-function

std::function它本身提供了一个很好的实用程序——它提供了类型删除,以便一般地存储/提供对可调用对象的访问。它的灵 active 很好:

#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 s 作为它的参数。

虽然直观,但我相信我对 显式模板参数缺乏基本理解。 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 一起使用时,直观的显式模板参数究竟表示了什么? ?

最佳答案

What exactly is the type with omitted *?

考虑一下。一个类型“后跟”一个 * 表示“指向该类型的指针”。如果您没有使用 *“跟随”一个类型,那么该类型就意味着该类型。所以如果你有一个函数指针,那么它就是一个指向...函数类型的指针。

因此,像 void() 这样的类型是函数类型。

函数类型不同于对象类型,但它们仍然是类型。因此,您可以使用它们玩 C++ 允许的大多数基于类型的游戏。但由于它们不是对象类型,所以不能创建函数类型的对象。

关于c++ - 传递给 std::function 模板的模板参数究竟代表什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304151/

相关文章:

c++ - C++ 中一组集合的高效集合交集

C++:如何将 GUID 设置为 NULL 而不是 GUID_NULL?

c++ - 添加新项目时,在 wtl 中滚动 clistviewctrl

c++ - "assert (this)"是可行的模式吗?

c++ - 函数指针如何工作?

c - 函数参数无效

c++ - 使用 `std::function` 从另一个对象调用一个对象的成员

c - 给定3个整数,每个整数执行一个数学运算。输入任何整数并执行其任务,而无需使用比较语句。

c++ - std::function 中的冗余构造函数重载?

C++ std::function 从派生类绑定(bind)