变分模板和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))... };
}