繁体   English   中英

如何减小数组参数的大小?

[英]How can I reduce the size of an array argument?

我有一个模板函数bar,它将对数组的引用作为参数。 我想将参数传递给另一个函数,但前提是将数组的大小减一,然后跳过数组的第一个元素。

#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)

但以上内容无效-您无法将const char *强制转换为const char [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]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM