可变参数模板和C数组

Jos*_*G79 6 c++ variadic-templates c++11

我正在尝试编译以下代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

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’
Run Code Online (Sandbox Code Playgroud)

注意关于寻找指针的部分.这在clang中也是如此,所以显然这是标准兼容的.有没有办法保留这是一个C数组而不转换为指针?

yur*_*hek 6

是.使用完美转发:

#include <utility>

template<class ...Us> void mycall(Us&&... args) {
    int xs[] = { args_fwd_(std::forward<Us>(args))... };
}
Run Code Online (Sandbox Code Playgroud)