如何减小数组参数的大小

How can I reduce the size of an array argument?

本文关键字:参数 何减小 数组      更新时间:2023-10-16

我有一个模板函数bar,它将对数组的引用作为参数。 我想获取参数并将其传递给另一个函数,但只有在将数组的大小减小 1 并跳过数组的第一个元素之后。

#include <iostream>
template <typename T>
void foo(const T& t)
{
  std::cout << sizeof(t) << std::endl;
  std::cout << t[0] << std::endl;
}
template <typename T>
void bar(const T& t)
{
  std::cout << sizeof(t) << std::endl;
  std::cout << t[0] << std::endl;
  foo(t); // Magic is desired here!
}
int main()
{
  char array[] = "ABCD";
  bar(array);
}

以上打印出来:

5
A
5
A

我希望它打印出来:

5
A
4
B

您可以使用两个模板参数执行此操作,一个用于数组类型,另一个用于数组大小。

template <typename T, int N>
void bar(const T (&t)[N])
{
    // ...
    foo(reinterpret_cast<const T(&)[N-1]>(t[1]));
}
可能需要

复制数组才能获取引用。我希望这个答案能引起人们对您问题的真正主题的关注。

使用外观适当(和通用)的转换调用 foo 如下所示

reinterpret_cast<typename std::remove_reference<decltype(t[0])>::type [sizeof(t)-1]>(t+1)

但上述内容无效 - 您不能将常量字符*转换为常量字符[4];此外,您无法以其他方式获取引用,因为无法复制构造数组。因此,您可能需要在 c++11 中复制或使用 std::array,这实际上归结为有两个模板参数。

但是,这是一个有效的解决方案:

typedef typename std::remove_reference<decltype(t[0])>::type  element_type;
foo(reinterpret_cast<element_type(&) [sizeof(T)-1]>(t[1]));