const指针和const数组

时间:2015-10-20 14:53:27

标签: c++ arrays operators overloading

当我们有两个运算符用于输出对象和这些对象的数组,并尝试输出常量对象的数组时,涉及对象的运算符。有没有办法强制数组操作符使用c数组的常量对象?

示例代码:

#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;
}

输出:1 2 1 1

此外,在我的情况下,2运算符使用1作为输出。

2 个答案:

答案 0 :(得分:1)

根据标准草案N4527 8.5 / p7.3初始化[dcl.init] 强调我的):

  
      
  • 否则,不执行初始化。
  •   
     

如果程序要求   const限定类型T,T的对象的默认初始化   应该是具有用户提供的默认构造函数的类类型

因此,您必须为class C定义一个默认构造函数,以便解决此问题。

答案 1 :(得分:1)

我现在会做类似的事情。如果有人知道更好的解决方案,请写下来。

#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;
}
相关问题