下面的代码片段简单地创建了一个具有三个成员的结构。其中之一是回调函数。我想初始化一个由这些结构组成的数组,但是我不知道语法,在这里我可以拥有具有不同原型的多个回调。
#include <iostream>
#include <functional>
template <typename Func>
struct Foo
{
Foo(int a, int b, Func func):
_a{a},
_b{b},
_func{func}{}
int _a;
int _b;
Func _func;
};
int main() {
auto test = [](){std::cout << "hello\n";};
Foo<std::function<void(void)>> foo(5,10, test);
foo._func();
//array version
//......................
}
答案 0 :(得分:2)
怎么样
//array version
Foo<std::function<void(void)>> a[] = { {5, 10, test}, {1, 2, test} };
答案 1 :(得分:1)
根据您要使用的“数组”,我认为创建起来很简单,这里使用std :: vector。您可以使用任何您喜欢的容器。使用[]完成此处的访问,但也可以使用at()
方法
typedef Foo<std::function<void(void)>> FooTypeDef;
int main() {
auto test = [](){std::cout << "hello\n";};
FooTypeDef foo(5,10, test);
foo._func();
//array version
//......................
std::vector<FooTypeDef> array;
array.push_back(foo);
array.push_back(foo);
array[0]._func();
array[1]._func();
}
也许使用typedef;)