通过引用调用数组

a13*_*37q 1 c++ arrays

我想做的是这样的:

void dosth(bool& a) {
  a[2] = false;
}

int main() {
  bool a[10];

  dosth(a);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想通过引用调用,以数组作为参数.怎么实现这个?

谢谢

GMa*_*ckG 8

像这样:

typedef bool array_type[10];

void dosth(array_type& a)
{
    a[2] = false;
}

int main()
{
    array_type a;
    dosth(a);
}
Run Code Online (Sandbox Code Playgroud)

或者没有typedef:

void dosth(bool (&a)[10])
{
    a[2] = false;
}

int main()
{
    bool a[10];
    dosth(a);
}
Run Code Online (Sandbox Code Playgroud)

或者更一般地说:

template <size_t Size>
void dosth(bool (&a)[Size])
{
    /*static_*/assert(Size > 2);

    a[2] = false;
}

int main()
{
    bool a[10];
    dosth(a);
}
Run Code Online (Sandbox Code Playgroud)

如果你不在C++ 0x中,你可以static_assert像这样实现一个(简单):

template <bool>
struct static_assert_type;

template <> // only true is defined
struct static_assert_type<true> {}

#define static_assert(x) { static_assert_type<(x)>(); }
Run Code Online (Sandbox Code Playgroud)

static_assert如果数组大小太小,它允许您取消注释并获得编译时错误.


Mik*_*our 5

您可以允许数组衰减为指针,如Philippe的答案.更加类型安全的解决方案是,只接受数组并允许编译时范围检查

template <size_t SIZE>
void dosth(bool (&a)[SIZE])
{
    a[2] = false;
}
Run Code Online (Sandbox Code Playgroud)

如果索引超出范围,您可以添加static_assert(SIZE > 2);(或者BOOST_STATIC_ASSERT(SIZE > 2);如果您的编译器不支持static_assert)给出编译错误.