简体   繁体   中英

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. 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

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]; 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.

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]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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