【问题标题】:Generic function holder in c++C++中的通用函数持有者
【发布时间】:2018-05-15 20:11:44
【问题描述】:

所以我知道如何在 C++ 中使用typedef

但是如果我想要一个泛型函数数组我可以做到吗?

例如:

foo() { cout << "hello world" << endl; }


foo2(int a) { cout << "hello friend number " << a << endl; }


var_type[] function_holder = { foo, foo2 }

function_holder[0]();
function_holder[1](1);

【问题讨论】:

  • 你可以创建一个指向相同类型函数的函数指针数组,但你不能将函数按值放入数组中。
  • std::anystd::variant 可能会有所帮助

标签: c++ function pointers generics typedef


【解决方案1】:

只需使用std::function:

std::function<void()> functions[] = { 
   foo, 
   std::bind( foo2, 1 )
};

for( auto f : functions ) f();

live example

【讨论】:

    猜你喜欢
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2019-04-20
    • 2016-10-23
    • 2019-08-10
    相关资源
    最近更新 更多