jeudi 28 mars 2019

How to write the constructor for a template class that wraps a container where the container can be both an array or a vector?

I wish to have a general template class that allows the user to pass the container to use:

template<class Container>
struct Sum
{
  Container m_terms;
...

Other classes will derive from that, for example,

class MySum : public Sum<std::vector<int>>
{
...

or

class MySum4 : public Sum<std::array<int, 4>>
{
...

The containers need to be initialized from the constructor. My idea at first was to use std::initializer_list, for example,

MySum ms{1, 2, 3, 4};

which would require the following constructors to be added:

template<class Container>
struct Sum
{
  Container m_terms;

  Sum(std::initializer_list<typename Container::value_type> const& il) :
    m_terms(il) { }
...

class MySum : public Sum<std::vector<int>>
{
  using Sum<std::vector<int>>::Sum;
...

but then how can I get MySum4 to work too? An array doesn't take a std::initializer_list<>.

Here is more complete code that shows the compiler error: https://wandbox.org/permlink/CZW3YaKdInwZZD8e

Aucun commentaire:

Enregistrer un commentaire