变分模板和C数组
Variadic templates and C arrays
本文关键字:数组 更新时间:2023-10-16
我正在尝试编译以下代码:
template <typename T, int N> void foo( const T (&array)[N]) {}
template <typename T> static int args_fwd_(T const &t) { foo(t); return 0; }
template<class ...Us> void mycall(Us... args) {
int xs[] = { args_fwd_(args)... };
}
int main(void) {
int b[4];
mycall(b);
}
mycall
函数使用可变模板,然后转发到args_fwd_
函数,以在每个参数上调用函数foo
。
这适用于大多数参数类型(假设我已经适当地定义了foo
函数)。但是,当我尝试传递C样式数组(int b[4]
)时,它会变成一个指针,然后它找不到需要数组(而不是指针)的模板化foo
函数。gcc 4.9.3中的错误如下:
error: no matching function for call to ‘foo(int* const&)’
note: candidate is:
note: template<class T, int N> void foo(const T (&)[N])
template <typename T, int N> void foo( const T (&array)[N]) {}
note: template argument deduction/substitution failed:
note: mismatched types ‘const T [N]’ and ‘int* const’
注意关于查找指针的部分。这在clang中也是一样的,所以显然这是符合标准的。有没有一种方法可以在不将其转换为指针的情况下保持这是一个C数组?
是。使用完美的转发:
#include <utility>
template<class ...Us> void mycall(Us&&... args) {
int xs[] = { args_fwd_(std::forward<Us>(args))... };
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '