Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array type deduction in a function template

I have a template method as follows:-

template<typename T, int length>
void ProcessArray(T array[length]) { ... }

And then I have code using the above method:-

int numbers[10] = { ... };
ProcessArray<int, 10>(numbers);

My question is why do I have to specify the template arguments explicitly. Can't it be auto-deduced so that I can use as follows:-

ProcessArray(numbers); // without all the explicit type specification ceremony

I am sure I am missing something basic! Spare a hammer!

like image 900
Higher-Kinded Type Avatar asked Jun 24 '12 17:06

Higher-Kinded Type


People also ask

What is template argument deduction?

Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.

What is type deduction c++?

Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.


2 Answers

You can't pass arrays by value. In a function parameter T array[length] is exactly the same as T* array. There is no length information available to be deduced.

If you want to take an array by value, you need something like std::array. Otherwise, you can take it by reference, which doesn't lose the size information:

template<typename T, int length>
void ProcessArray(T (&array)[length]) { ... }
like image 113
R. Martinho Fernandes Avatar answered Sep 21 '22 21:09

R. Martinho Fernandes


You're missing the correct argument type: arrays can only be passed by reference:

template <typename T, unsigned int N>
void process_array(T (&arr)[N])
{
    // arr[1] = 9;
}

double foo[12];
process_array(foo); // fine
like image 33
Kerrek SB Avatar answered Sep 22 '22 21:09

Kerrek SB