1

The following snippet of code simply creates a structure that has three members. One of them is a callback function. I would like to initialize an array of these structures but I don't know the syntax, where I can have multiple callbacks with varying prototypes.

#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
    //......................
}
tester123
  • 399
  • 1
  • 3
  • 10

2 Answers2

2

How about this

//array version
Foo<std::function<void(void)>> a[] = { {5, 10, test}, {1, 2, test} }; 
cigien
  • 57,834
  • 11
  • 73
  • 112
  • I am relatively new to C++, but the type of the function can't change correct. It has to be the same for all? – tester123 Apr 08 '20 at 15:28
  • Type and parameters can't change unfortunately: https://stackoverflow.com/questions/47332305/c14-generic-lambda-with-generic-stdfunction-as-class-member – RoQuOTriX Apr 08 '20 at 15:33
  • @tester123 the types don't *have* to be the same, but they must share a common type that can be used for the array type. – cigien Apr 08 '20 at 15:41
1

Depending on what "array" you want to use, I think the creation is straight-forward, here with std::vector. You can use any container you like. Accessing here done with [], but could also be done with the at() method

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();
}

And maybe use a typedef ;)

RoQuOTriX
  • 2,871
  • 14
  • 25