未知类型的 CIN >>函数模板参数
cin >> function template arg of unknown type
>我有一个函数模板和主要如下:
template <class type > type* calculate(type inputVal) {
type val;
static int counter = 0;
static type sum = inputVal;
static type average = inputVal;
static type* address = &sum
do {
cout << "Enter value: ";
cin >> val;
counter++;
sum += val;
average = sum / counter;
} while (!cin.eof());
return address;
}
void main() {
int num;
cout << "Enter Value: ";
cin >> num;
int *ptr = calculate(num);
cout << "SUM: " << *ptr << " AVG: " << *(ptr+1);
}
我的问题是这应该适用于不同的输入类型而不仅仅是 int,因此如果用户首先输入浮点数,它会将所有内容视为该类型,就像用户输入字符一样。
此外,模板函数无法打印结束值。
普通
变量sum
被视为指针算术的单元素数组(N3337 5.7 加法运算符),当ptr
指向它时,ptr+1
不指向有效对象,因此不得取消引用。如果需要连续内存区域,请使用数组。
另请注意
- 在更新
sum
和average
后检查!cin.eof()
似乎不是一个好主意,因为它将使用无效(重复)的数据。在处理数据之前检查输入是否成功。 - 在全局命名空间中声明
void main()
(或返回类型不是int
main
)在标准C++中是非法的。除非你有一些特殊的原因——例如,你的老板或老师禁止编写符合标准的代码——否则你应该使用int main()
(在这种情况下)。 - 您应该将
counter
初始化为1
以将inputVal
放入数字中。避免将输入作为参数以避免编写重复代码似乎更好。
试试这个:
#include <iostream>
using std::cin;
using std::cout;
template <class type > type* calculate(type inputVal) {
type val;
static int counter = 1;
static type buffer[2];
type& sum=buffer[0];
type& average=buffer[1];
sum=average=inputVal;
static type* address = buffer;
for(;;) {
cout << "Enter value: ";
if(!(cin >> val)) break;
counter++;
sum += val;
average = sum / counter;
}
return address;
}
int main() {
int num;
cout << "Enter Value: ";
cin >> num;
int *ptr = calculate(num);
cout << "SUM: " << *ptr << " AVG: " << *(ptr+1);
}
或者没有参数输入:
#include <iostream>
using std::cin;
using std::cout;
template <class type > type* calculate() {
type val;
static int counter = 0;
static type buffer[2];
type& sum=buffer[0];
type& average=buffer[1];
sum=0; // the type used has to be capable to be converted from integer 0
average = 0;
static type* address = buffer;
for(;;) {
cout << "Enter value: ";
if(!(cin >> val)) break;
counter++;
sum += val;
average = sum / counter;
}
return address;
}
int main() {
int *ptr = calculate<int>();
cout << "SUM: " << *ptr << " AVG: " << *(ptr+1);
}
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 将重载的成员函数传递给函数模板
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 具有常量引用参数的函数模板专用化
- std::span<const T> 作为函数模板中的参数
- 如何编写一个完美的缩写函数模板?
- 仅在函数模板中为那些定义了函数的类型执行函数
- 如何在C++中伪造虚拟可变参数函数模板?
- 以下代码中的函数模板有什么问题?
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 将显式实例化的函数模板与转换匹配
- 使用定义函数模板别名
- 函数模板返回类型
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++ std::functional 中的可变参数函数模板
- 单行函数模板 c++ 的内联性保证
- C++函数模板需要 &for 数组参数
- 概念解析为使用 std::make_signed_t 时意外的函数模板
- 两个函数模板候选项.将一个参数作为引用后,选择不太专业的模板