gpt4 book ai didi

c++ - 用数组引用调用

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:21 25 4
gpt4 key购买 nike

我想做的是这样的:

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

int main() {
bool a[10];

dosth(a);

return 0;
}

我想通过引用调用,将数组作为参数。如何实现?

谢谢

最佳答案

像这样:

typedef bool array_type[10];

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

int main()
{
array_type a;
dosth(a);
}

或者没有 typedef:

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

int main()
{
bool a[10];
dosth(a);
}

或者更一般地说:

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

a[2] = false;
}

int main()
{
bool a[10];
dosth(a);
}

如果您不使用 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)>(); }

这允许您取消对 static_assert 的注释,并在数组太小时得到编译时错误。

关于c++ - 用数组引用调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3670308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com