mercredi 30 octobre 2019

Can not construct a class from std::function when used inside std::vector

I want to have an std:array of std::function, but I want to make sure that all elements of the array are initialized. For that end I built a wrapper class that takes an std::function as a construction parameter.

But when I initialize an array of my wrapper class directly with my function (the one who should be inside std::function) it fails to compile.

Here is the problem, distilled:

#include <functional>
#include <array>

static void f() {}
using F = std::function<void(void)>;
enum { Count = 4 };

struct C
{
    //To get a compilation error when some
    //  elements of the array are not initialized.
    C() = delete;

    C(F) {}
};

//OK
static const C c {f};

//OK
static const std::array<F,Count> direct
{
    F{f},
    {f},
    f,
    f
};

static const std::array<C,Count> wrapper
{
    F{f},   //OK
    C{f},   //OK
    {f},    //OK
    f       //could not convert 'f' from 'void()' to 'C'
};

I tried changing the array to an std::vector<C> (although it defeats my whole purpose of using an std:array to begin with) and it refuses to compile any of the above initializations.

Aucun commentaire:

Enregistrer un commentaire