Pointer output const and const array

When we have two operators for outputting an object and an array of these objects, and we try to output an array of constant objects, the operator for objects is involved. Is there any way to get the operator for arrays to work with arrays of persistent objects?

Code example:

#include <iostream>
#include <cstddef>

using std::size_t;

namespace nm
{
  struct C { int i; };

  template <size_t N>
  using c_c_array = C[N];

  inline std::ostream& operator << (std::ostream& lhs,  C const*) { return lhs << "1\n"; }

  template <size_t N>
  inline std::ostream& operator << (std::ostream& lhs,  c_c_array<N> const&) { return lhs << "2\n"; }

}

int main()
{
  nm::C c{1};

  nm::C arr[5];

  nm::C const c_const{1};

  nm::C const arr_const[5] {{1}, {1}, {1}, {1}, {1}};

  std::cout << &c   // 1 - ok
            << arr  // 2 - ok
            << &c_const   // 1 - ok
            << arr_const; // 1 --ups

  return 0;
}

Exit: 1 2 1 1

In addition, operator 2 in my case uses output 1.

+4
source share
2 answers

Now I will do something like the one shown below. If someone knows the best solution, please write.

#include <iostream>
#include <cstddef>
#include <type_traits>

using std::size_t;

namespace nm
{
  struct C { int i; };

  template <size_t N>
  using c_c_array = C[N];

  template<typename T>
  inline
  std::enable_if_t<std::is_same<T, C*>::value || std::is_same<T, C const*>::value,
  std::ostream&>
  operator << (std::ostream& lhs,  T const&) { return lhs << "1\n"; }

  template <size_t N>
  inline std::ostream& operator << (std::ostream& lhs,  c_c_array<N> const&) { return lhs << "2\n"; }

}

int main()
{
  nm::C c{1};

  nm::C arr[5];

  nm::C const c_const{1};

  nm::C const arr_const[] {1,2,3,4,5};

  std::cout << &c   // 1 - ok
            << arr  // 2 - ok
            << &c_const   // 1 - ok
            << arr_const; // 1 --ups

  return 0;
}
+1
source

N4527 8.5/p7.3 [dcl.init] ( Mine):

  • .

const, T, T .

, class C.

+1

Source: https://habr.com/ru/post/1612454/


All Articles