Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2003-02-05 07:34:50


>From: "Terje Slettebø" <tslettebo_at_[hidden]>

> const int array[3];
>
> std::cout << array;
>
> MSVC 7 - C
> Intel C++ 7 - C
> g++ 3.2 - C
>
> const char array[3];
>
> std::cout << array;
>
> MSVC 7 - A (S or C)
> Intel C++ 7 - C
> g++ 3.2 - C
>
> std::cout << "Test";
>
> MSVC 7 - A (S or C)
> Intel 7 - C
> g++ 3.2 - A (S or C)
>
> In order to allow string literals to be used, without ambiguity or the
wrong
> operator being selected, it seems that one needs to overload operator<< on
> something else than T(&)[N]. T[N] isn't an option, either, as this is the
> same as overloading on T *, which means it isn't able to deduce N.
>
> This quandary may be solved by wrapping arrays in an object, which then is
> passed to the overloaded operator<<. For example:
>
> std::cout << wrap_array(array);

I found that boost::ref works for this, as well, so you may use:

char array[3[[3][3];

std::cout << array; // Overloading for this gives wrong handling of string
literals, on all compilers.

std::cout << cref(array); // Ok

For example:

void array3D_test()
{
  char boards[3][3][3]=
  {
    {
      {'X','O','X'},
      {'O','X','O'},
      {'X','O','X'}
    },
    {
      {'X','X','X'},
      {'X','O','X'},
      {'X','X','X'}
    },
    {
      {'O','X','O'},
      {'X','X','X'},
      {'O','X','O'}
    }
  };

  std::cout << composite_format<boost::reference_wrapper<char (&)[3]>
>("\n|","|\n","|")
            << composite_format<boost::reference_wrapper<char (&)[3][3]>
>("-------","-------","-------")
            << composite_format<boost::reference_wrapper<char (&)[3][3][3] >
>("--- Boards ---\n\n","\n\n--- Boards ---","\n\n")
            << boost::cref(boards) << '\n';
}

Output:

--- Boards ---

-------
|X|O|X|
-------
|O|X|O|
-------
|X|O|X|
-------

-------
|X|X|X|
-------
|X|O|X|
-------
|X|X|X|
-------

-------
|O|X|O|
-------
|X|X|X|
-------
|O|X|O|
-------

--- Boards ---

I'll work on a version that works with this.

Regards,

Terje


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk