I'm trying to compile the following piece of code:
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 variadic templates and then forwards to the args_fwd_
function to call the function foo
on each argument.
This works fine for most argument types (assuming I have appropriately defined foo
functions). But when I try to pass a C-style array (int b[4]
) it gets turned into a pointer and then it can't find the templated foo
function that requires an array (not pointer). The error from gcc 4.9.3 is as follows:
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’
Note the part about looking for a pointer. This is the same in clang as well so apparently this is standard compliant. Is there a way to preserve that this is a C array without it getting converted to a pointer?
Yes. Use perfect forwarding:
#include <utility>
template<class ...Us> void mycall(Us&&... args) {
int xs[] = { args_fwd_(std::forward<Us>(args))... };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With