简体   繁体   English

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

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

I've got a template function, bar, that takes a reference to an array as a parameter. 我有一个模板函数bar,它将对数组的引用作为参数。 I'd like to take the argument and pass it to another function, but only after reducing the size of the array by one, and skipping past the first element of the array. 我想将参数传递给另一个函数,但前提是将数组的大小减一,然后跳过数组的第一个元素。

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

The above prints out: 上面打印出:

5
A
5
A

I'd like it to print out: 我希望将其打印出来:

5
A
4
B

You can do this with two template parameters, one for the array type and one for the size of the array. 您可以使用两个模板参数来执行此操作,一个用于数组类型,一个用于数组大小。

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

Copying the array may be necessary to get a reference. 复制数组可能是获取参考所必需的。 I hope this answer will draw attention to the real subject of your question.. 我希望这个答案能引起您对问题真正主题的关注。

Calling foo with an appropriate-looking (and generic) cast looks as follows 用适当外观(和通用)的强制转换调用foo如下所示

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

but the above is invalid - you cannot cast const char* to const char[4]; 但以上内容无效-您无法将const char *强制转换为const char [4]; Also you cannot obtain a reference in another way since an array cannot be copy constructed. 另外,由于无法复制构造数组,因此无法以其他方式获取引用。 So you may need to either copy or use std::array in c++11, which really boils down to having two template parameters. 因此,您可能需要在c ++ 11中复制或使用std :: array,这实际上归结为具有两个模板参数。

Here is a valid solution however: 但是,这是一个有效的解决方案:

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