Wes Field
Wes Field

Reputation: 3441

Identifying C++ Template Constraints

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

Answers (2)

Ralph Tandetzky
Ralph Tandetzky

Reputation: 23610

  1. T must be an object-type and not a reference because const T a[] must be a valid parameter declaration.
  2. T must be movable or copyable since it's the return type.
  3. T must be copy-constructible due to T sum = a[0].
  4. T must allow t += s for objects of type T due to sum += a[i].
  5. T must be divisible by an integer because of sum/size.
  6. The result of the devision must be a T or must be at least implicitly convertible to T because the function returns a T.

Upvotes: 4

Jiminion
Jiminion

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

Related Questions