Variadic Templates and C Arrays

I am trying to compile the following code snippet:

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); } 

The mycall function uses variational patterns, and then proceeds to the args_fwd_ function to call the foo function for each argument.

This works great for most types of arguments (assuming I have the corresponding foo functions). But when I try to pass an array of C-style ( int b[4] ), it turns into a pointer, and then cannot find the template function foo , which requires an array (not a pointer). The gcc 4.9.3 error looks like this:

 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' 

Pay attention to the index search part. This is the same in clang, so this seems to be a standard match. Is there a way to keep this a C array without converting it to a pointer?

+6
source share
1 answer

Yes. Use perfect forwarding:

 #include <utility> template<class ...Us> void mycall(Us&&... args) { int xs[] = { args_fwd_(std::forward<Us>(args))... }; } 
+6
source

All Articles