c++ - 为什么我可以将可调用目标存储在与类型不匹配的 std::function 中

标签 c++ c++11 stdbind

我尝试了以下方法:

typedef std::function<void(int)> callback;

struct testclass
{
    void testfunc()
    {
        printf("test\n");
    }
};

int main()
{
    testclass test;
    callback c = std::bind(&testclass::testfunc, &test);
    c(1);
}

输出是

test

std::bind 返回一个可调用目标,如 void(void),而回调应存储为 void(int) .

为什么我可以这样做?

最佳答案

std::bind返回一个函数对象,它忽略任何没有关联占位符的参数。这是一场松散的比赛。

例如:

auto f = []{}; // no arguments, do nothing
f(1); // obviously ill-formed

auto g = std::bind(f);
g(); // okay, calls f()
g(1); // okay, calls f()
g(1, 2); // okay, calls f()

在您的示例中,您有一个 function<void(int)>您正在使用 std::bind() 的结果进行初始化调用没有占位符。那很好用。 int function 的参数只是被忽略了。它可能是也可能不是您真正想要做的,但它是完全有效的代码。


使用 lambda,您可以通过以下方式获得相同的效果:

callback c = [&test](int){ test.testfunc(); };

这里我们必须显式地写参数,而 bind它被隐含地忽略了。

关于c++ - 为什么我可以将可调用目标存储在与类型不匹配的 std::function 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969341/

相关文章:

c++ - 按类型访问具有重复类型的 std::tuple 应该会产生编译错误

c++ - 搜索一组独特的指针

c++ - 如何使用 QxtGlobalShortcut 库检测 Qt 中的按键释放事件

c++ - 与 Clang 和 Boost 1.48 一起工作的多播委托(delegate)/信号库?

c# - C# 或 VB.NET 中的 std::bind 等价物

c++ - 函数如何在递归后执行 Action ?

c++11 - 捕获引用的一致性

c++ - 绑定(bind)到私有(private)继承的成员函数

C++ - std::bind call operator() 完美转发

c++ - 如何在 Eclipse IDE 上显示语法着色和范围界定?