【问题标题】:How to typedef std::function with unsigned char array as pararmeter如何使用 unsigned char 数组作为参数来 typedef std::function
【发布时间】:2022-11-16 12:01:19
【问题描述】:

我试图将许多函数指针推入一个向量以供以后使用。但是,我遇到了类型问题

/// in the h file
typedef std::function<int(unsigned char *)> func_t;

class A
{
  void init();
  // after some codes declaration
  private:
  B b;
  std::vector<func_t> func_list;

}

class B
{
   int somefunction(unsigned char *);
}

// elsewise in the cpp file of class A
A::init()
{
  func_t f = std:bind(&B::somefunction, &b, std::placeholders::_1);
  func_list.push_back(f);
}

错误似乎发生在 std::bind 点,错误读作

 initializing: cannot convert from 'std::Binder<std::Unforced, void(__thiscall B::*)(unsigned char *), B*, const std::_Ph<1> &>' to std::function<int(unsigned char*)>

如果我将变量 f 从 func_t 更改为 auto ,问题就会消失。尽管随后我会遇到同样的问题来推入向量 func_list。所以我想我的问题是类型定义或 std::bind 定义

谢谢

【问题讨论】:

  • 似乎对我有用:godbolt.org/z/j4j7d9vhe 你的编译器和 C++ 版本是什么?
  • @Ranoiaetep 我认为它会编译,但你应该得到一个运行时错误
  • @Ranoiaetep nvm,你是对的..不知道为什么我得到了 OP 一开始做的同样的错误..

标签: c++ bind


【解决方案1】:

std::bind 返回“未指定类型 T 的函数对象,其中 std::is_bind_expression::value == true”cppreference

我认为没有办法绑定返回 func_t(根据convert std::bind to function pointer),但我可能错了。

编辑:正如@Ranoiaetep 指出的那样,将其保留为 func_t 而不更改为 auto,也可以。

更改为 auto 确实有效:

#include <iostream>
#include <functional>
#include <vector>

using namespace std;
typedef std::function<int(unsigned char *)> func_t;

class B
{
public:
int somefunction(unsigned char *);
};

int B::somefunction(unsigned char *) {
    return 1;
};

class A
{
    public:
  void init();
  private:
  B b;
  std::vector<func_t> func_list;

};

void A::init()
{
  auto f = std::bind(&B::somefunction, &b, std::placeholders::_1);
  func_list.push_back(f);
};

int main()
{
    A* a = new A();
    a->init();
    return 0;
}

【讨论】:

  • 您不能将绑定表达式转换为函数指针。但是,std::function 可以存储任何CopyConstructible Callable,其中包括绑定表达式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多