【问题标题】:Accept any function (but only functions) as a parameter接受任何函数(但仅限函数)作为参数
【发布时间】:2014-08-23 11:48:14
【问题描述】:

有没有办法接受任何函数签名作为参数?例如:

void accepter(void (*func)(int)) {  ... }

可以接受void (*)(int) 类型的任何内容。我知道我可以使用模板,例如:

template<class T>
void accepter(T func) { ... }

这会起作用,但它允许传入非函数。如何只过滤函数,就像 void * 过滤任何类型的指针一样?

【问题讨论】:

  • 如果你试图调用它,你会得到一个编译时错误。你在做什么,你得到一个链接时间错误?我看到的唯一方法是,如果您仅为函数类型显式实例化模板,但您似乎没有这样做......
  • 取函数的地址(jit编译器)
  • 这仍然不会导致链接时错误。
  • 是的,我想这是真的。我将编辑我的问题。
  • 使用 C++11 std::function 或 boost::function,例如stackoverflow.com/questions/2304203/…

标签: c++


【解决方案1】:

使用 C++11 的 std::function 应该可以工作:

#include <functional>

template<typename T>
void test (std::function<T> func) {    

你可以使用这个,例如:

int foo (int);
std::sting bar (bool);

test(std::function<int(int)>(foo));
test(std::function<std::string(bool)>(bar));

【讨论】:

  • 很遗憾std::function 没有隐式转换。不过这行得通!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 2018-06-03
  • 1970-01-01
  • 2022-01-09
  • 2021-03-29
  • 1970-01-01
相关资源
最近更新 更多