Reputation: 439
Consider the following code :
template <class T>
T average(T *atArray, int nNumValues)
{
T tSum = 0;
for (int nCount = 0; nCount < nNumValues; nCount++)
{
tSum += atArray[nCount];
}
tSum = tSum / nNumValues;
return tSum;
}
Which of the following statements about the class/type T must be true in order for the code to compile and run without crashing?
My Thoughts:
I think it could be something apart from numeric type but it will need to have the operator + and / well defined.
point 2 seems incorrect as < has no relation with / and + operator
same with point 3 and point 4.
Although I am not sure about my reasoning above.
Upvotes: 0
Views: 70
Reputation: 72401
std::complex<double>
) could work.<
is only used on int
expressions, not involving T
.atArray[nCount]
expression uses a T*
pointer, not an expression with type T
, so it has the built-in meaning.T
could be a class with normal assignment operator, deleted copy constructor, and public non-deleted move constructor.Probably the intended answer is #4.
The actual requirements on T
are:
T
can be copy-initialized from an int
, or from a null pointer constant. (0
is a special expression which can do two different things...)T
is a numeric type, or an enumeration or class type with valid operator functions supporting expressions:
a += b
and a = b
, where a
and b
are lvalues of type T
a / n
, where a
is an lvalue of type T
and n
is an lvalue of type int
T
is move-constructible.Upvotes: 0
Reputation: 117308
operator+=
defined.T
T
, only a T*
and pointer types all have this operator defined.delete
d and the question says "and" so the answer is no. It needs some kind of assignment operator though.Consider this class, especially constructed to be able to answer no to as many questions as possible:
struct foo {
foo() = default;
foo(int) {} // implicit conversion from int
foo(const foo&) = delete; // no copy constructor
foo(foo&&) = default; // but move constructor
foo& operator=(const foo&) = delete; // no copy assignment
foo& operator=(foo&&) = delete; // no move assignment
foo& operator=(int) { return *this; }; // but assignment from int
foo& operator+=(const foo&) { return *this; } // for tSum += atArray[nCount];
operator int() const { return 1; } // implicit conversion to int
};
And it would work fine with the function template:
int main() {
foo arr[2];
auto x = average(arr, 2);
}
Upvotes: 1