vendredi 30 décembre 2016

Variadic template not working with an initializer list

I created a factory function template:

template <typename M, typename... Args>
std::shared_ptr<M> create(Args... args)
{
    return std::make_shared<M>(args...);
}

And a simple container:

struct Group {
    std::vector<int> vec;
    Group(std::initializer_list<int> il) : vec(il) {}
};

Then I try to create a Group

int main()
{
    auto gr = create<Group>({1, 2, 3});
    return 0;
}

This doesn't compile,

error: no matching function for call to 'create'
    auto gr = create<Group>({1, 2, 3});
candidate function not viable: requires 0 arguments, but 1 was provided
std::shared_ptr<M> create(Args... args)
                   ^

but if I use a temporary variable:

int main(int argc, char *argv[])
{
    std::initializer_list<int> il = {1, 2, 3};
    auto gr = create<Group>(il);
    return 0;
}

it does. Why?

Aucun commentaire:

Enregistrer un commentaire