如何减小数组参数的大小
How can I reduce the size of an array argument?
我有一个模板函数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]));
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- "return-by-reference"或"pass-by-reference"参数何时与constexpr兼容?