How to populate const member array based on constructor argument?

Say I have this class:

template<int N>
class A {
    public:
    A(const char *s) ...
    private:
    const char buf[N];
};

This template exists, so I can adjust the size of the array without dynamic memory allocation (requirement). An element bufmatters constbecause it must remain constant for the lifetime of the object after the initialization of the object.

To clarify, I also do not have access to the STL.

What are my options for defining this constructor so that I can copy the contents sto buf? One option is const_cast, but I'm looking for alternatives that don't require this.

+4
source share
2 answers

, @Richard Hodges, , char, char const*, . , , :

template<int N>
class A 
{
       template<size_t...Is>
       A(const char * s, std::index_sequence<Is...>)
        : _assert(std::strlen(s) <= N, "size of buffer is bigger than N"), 
          buf{ (Is, *s != '\0'? *s++: *s)... }
        {}

    public:
        A(const char *s) : A(s, std::make_index_sequence<N>()) {}

    private:
       throwable  _assert;
       const char  buf[N];
};

throwable :

 struct throwable
 {
    throwable(bool b, char const * message){
      if (not b) 
          throw std::invalid_argument(message);
    }
 };

throwable , buf , , N . , , , , , , . , , , .

, _assert . , :

template<int N>
class A : private throwable
{
       template<size_t...Is>
       A(const char * s, std::index_sequence<Is...>)
        : throwable(std::strlen(s) <= N, "size of buffer is bigger than N"), 
          buf{ (Is, *s != '\0'? *s++: *s)... }
        {}
    public:
        A(const char *s) : A(s, std::make_index_sequence<N>()) {}

    private:
       const char  buf[N];
};

1 .

+4

index_sequence .

#include <utility>
#include <cstdlib>


template<int N>
class A {

  template<size_t...Is>
    A(const char (&s)[N], std::index_sequence<Is...>)
    : buf{ s[Is]... }
  {}


    public:
    A(const char (&s)[N]) 
      : A(s, std::make_index_sequence<N>())
    {
    }

    private:
    const char buf[N];
};


int main()
{
  A<3> a("ab");

};

const char [] , constexpr:

#include <utility>
#include <cstdlib>


template<int N>
class A {

  template<size_t...Is>
    constexpr A(const char (&s)[N], std::index_sequence<Is...>)
    : buf{ s[Is]... }
  {}


    public:
    constexpr A(const char (&s)[N]) 
      : A(s, std::make_index_sequence<N>())
    {
    }

    private:
    const char buf[N];
};


int main()
{
  constexpr A<3> a("ab");

};

...

ok, :

#include <utility>
#include <cstdlib>
#include <cstring>


template<int N>
class A {

  template<size_t...Is>
    constexpr A(const char *s, size_t len, std::index_sequence<Is...>)
    : buf{ (Is <= len ? s[Is] : char(0))... }
  {}


    public:
    constexpr A(const char *s) 
      : A(s, strlen(s), std::make_index_sequence<N>())
    {
    }

    private:
    const char buf[N];
};


int main()
{
  constexpr A<10> a("ab");

};
+3

All Articles