0

I would like to overload operator << combined with the comma operator in order to provide a way of assigning multiple comma-separated values to a std::array or std::vector class member.

For example, given the following class declaration:

class MyClass{
public:
   MyClass() {}
   ~MyClass() {} 
private:
   std::array<double, 5> a_{};
}

I would like to be able to use the following syntax:

MyClass m;
m << 9, 10, 11, 99, 5;

Which in turn would update a_ by setting the corresponding values (9 at a_[0], 10 at a_[1] and so on). Operator << should also raise an error if the number of comma-separated values does not match std::array::size

Thanks for any advice on how to proceed!

BigONotation
  • 4,406
  • 5
  • 43
  • 72
  • 2
    Might I suggest just overloading `<<` and using initializer lists instead? Then it would look like `m << {1, 2, 3}` instead. The logic should be much simpler. – Claudiu Jun 30 '16 at 22:55
  • 2
    Have you considered using [std::initializer_list](http://en.cppreference.com/w/cpp/utility/initializer_list) instead? `MyClass m{9, 10, 11, 99, 5};` would be more recognizable to more programmers. – user4581301 Jun 30 '16 at 22:55
  • 1
    You could take a look at [Boost.Assign](http://www.boost.org/doc/libs/1_61_0/libs/assign/doc/index.html) and see if it meets your needs. – Blazo Jun 30 '16 at 22:56
  • First of all you need to implement an overloaded `operator<<` for your class. Then you need to make it return some object which have an overloaded `operator,` function which in turn returns itself (or another instance of the same class which overloads the comma operator). But that's a lot of work instead of implementing a constructor to handle it properly (either though a variable number of arguments somehow, or better yet through an `std::initializer_list`). – Some programmer dude Jun 30 '16 at 22:56
  • 3
    Overloading `,` operator might look [suspicious](http://stackoverflow.com/a/5602136). – AlexD Jun 30 '16 at 23:00
  • @user4581301 Yes sorry about that I corrected it – BigONotation Jun 30 '16 at 23:00
  • Gordie Howe, Guy Lafleur, Mark Messier, Wayne Gretzky, and Guy Lapointe. Those are some good numbers. – user4581301 Jun 30 '16 at 23:04
  • @JoachimPileborg The idea is to provide a convenient syntax. I want to mimic what Eigen does for initializing Matrices: https://eigen.tuxfamily.org/dox/group__TutorialAdvancedInitialization.html – BigONotation Jun 30 '16 at 23:04
  • @JoachimPileborg Thanks though for putting me on the right track! – BigONotation Jun 30 '16 at 23:10
  • @Claudiu Yes that would also be a good option. – BigONotation Jun 30 '16 at 23:20

0 Answers0