Reputation: 3441
so I need a bit of help /tips identifying template constraints in C++. Here is some example code that contains 6 total constraints. I can find the obvious ones but can't identify all 6...
template <class T>
T avg(const T a[], int size)
{
T sum = a[0];
for (int i = 1; i < size; i++)
sum += a[i];
return sum/size;
}
A short explanation about each constraint or groups of constraints would be nice. Thanks for the help.
Upvotes: 0
Views: 199
Reputation: 23610
T
must be an object-type and not a reference because const T a[]
must be a valid parameter declaration. T
must be movable or copyable since it's the return type. T
must be copy-constructible due to T sum = a[0]
. T
must allow t += s
for objects of type T
due to sum += a[i]
. T
must be divisible by an integer because of sum/size
. T
or must be at least implicitly convertible to T
because the function returns a T
. Upvotes: 4
Reputation: 5168
1-2. a must be array, of type T.
3. size must be an int.
4. size must be less than or equal to length of a.
5. variable receiving return must be type T.
6. array must be length 1 or more.
Upvotes: 0