可变参数模板和 C 数组
Variadic templates and C arrays
我正在尝试编译以下代码:
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))... };
}
我正在尝试编译以下代码:
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))... };
}