Create the C++ Function Template named sumMultiPowers() so that it has three parameters sum, x, and n. The first two parameters will have the type represented by the function template type parameter T. n will always be int. The return type is void. All parameters are passed by value except for sum which is passed by reference. A Template Function created from sumMultiPowers() will compute sum = 1 + x + 2x^2 + 3x^3 + ... + nx^n
时间: 2024-01-05 15:03:02 浏览: 169
Sure, here's the C++ function template named `sumMultiPowers()`:
```c++
template<typename T>
void sumMultiPowers(T& sum, T x, int n) {
sum = 1;
T power_of_x = 1;
for (int i = 1; i <= n; i++) {
power_of_x *= x;
sum += i * power_of_x;
}
}
```
Here's how you can use this function template:
```c++
int main() {
double sum_double;
sumMultiPowers(sum_double, 2.0, 3);
std::cout << "sum_double = " << sum_double << std::endl; // output: sum_double = 29
int sum_int;
sumMultiPowers(sum_int, 2, 3);
std::cout << "sum_int = " << sum_int << std::endl; // output: sum_int = 29
}
```
Note that you can pass any type `T` that supports the `*=` and `+=` operators to this function template.