gpt4 book ai didi

C++11 将 std 函数绑定(bind)到重载的静态方法

转载 作者:行者123 更新时间:2023-12-05 00:49:07 25 4
gpt4 key购买 nike

这个问题对我来说似乎有点傻,但我找不到任何类似的问题,如果它是微不足道的,很抱歉

假设我们有一个结构:

struct C {
static void f(int i) { std::cerr << (i + 15) << "\n"; }
static void f(std::string s) { std::cerr << (s + "15") << "\n"; }
};

现在在别的地方:
std::function<void(int)> f1 = C::f; // this does not compile
void (*f2)(std::string s) = C::f; // this compiles just fine

我得到的错误是

error: conversion from ‘’ to non-scalar type ‘std::function’ requested



有没有办法在这种情况下使用 std::function ?我错过了什么?

谢谢

最佳答案

std::function<void(int)> f1 = C::f; // this does not compile

C::f是一个没有地址的重载集。您可以创建一个包装器 FunctionObject周围:
std::function<void(int)> f1 = [](int x){ return C::f(x); };

void (*f2)(std::string s) = C::f;   // this compiles just fine


此行编译是因为您正在“选择” std::string C::f 的过载通过显式将其分配给 void(*)(std::string) 来设置重载指针。

你可以对 f1 做同样的事情:
 std::function<void(int)> f1 = static_cast<void(*)(int)>(&C::f);

关于C++11 将 std 函数绑定(bind)到重载的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48262407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com