How to use boost::array with unknown size as object variable

I'd like to use boost::array as a class member, but I do not know the size at compile time. I thought of something like this, but it doesn't work:

int main() {
    boost::array<int, 4> array = {{1,2,3,4}};
    MyClass obj(array);
}

class MyClass {
    private:
        boost::array<int, std::size_t> array;
    public:
        template<std::size_t N> MyClass(boost::array<int, N> array)
        : array(array) {};
};

The compiler, gcc, says:

error: type/value mismatch at argument 2 in template parameter list for
  ‘template<class _Tp, long unsigned int _Nm> struct boost::array’
error:   expected a constant of type ‘long unsigned int’, got ‘size_t’

Which obviously means that one cannot use variable-sized arrays as class members. If so, this would negate all the advantages of boost::array over vectors or standard arrays.

Can you show me what I did wrong?

Answers


Boost's array is fixed-size based on the second template parameter, and boost::array<int,4> is a different type from boost::array<int,2>. You cannot have instances of the same class (MyClass in your example) which have different types for their members.

However, std::vectors can have different sizes without being different types:

struct MyClass {
  template<std::size_t N>
  explicit
  MyClass(boost::array<int, N> const& array)
  : data(array.begin(), array.end())
  {}

private:
  std::vector<int> data;
};

int main() {
  boost::array<int, 4> a = {{1,2,3,4}};
  MyClass obj(a);

  boost::array<int, 2> a2 = {{42,3}};
  MyClass obj2(a2);

  // notice obj.data.size() != obj2.data.size()

  return 0;
}

That said, boost::array is still useful (it's even useful in this example code), just not in the exact way you want to use it.


Need Your Help

Error: Bootstrap's JavaScript requires jQuery

javascript jquery html ajax twitter-bootstrap

When i run my site on mozilla i got this error above.Here some code snippet which might be helpful

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.