vendredi 25 septembre 2015

Variadic template and copy constructors

Why does the following not compile:

struct a
{
    int i;
};


template <typename T>
class b
{
public:
    T mItem;


    template <typename... Arguments>
    b(Arguments&&... args) : mItem(std::forward<Arguments>(args)...)
    {
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    b<a>(1);

    return 0;
}

error C2664: 'a::a(const a &)' : cannot convert argument 1 from 'int' to 'const a &'

But simply adding an extra argument like this make it compile:

struct a
{
    int i;
};


template <typename T>
class b
{
public:
    T mItem;


    template <typename... Arguments>
    // just random extra argument
    b(int, Arguments&&... args) : mItem(std::forward<Arguments>(args)...)
    {
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    b<a>(1);

    return 0;
}

Is there a cleaner way than simply adding an extra (useless) argument to b's constructor?

Aucun commentaire:

Enregistrer un commentaire