c++ - 模板参数的有效对象
问题描述
考虑以下代码:
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;
}
以及关于它的以下问题:
以下关于类/类型 T 的哪些陈述必须为真,才能使代码编译和运行而不会崩溃?
- 它必须是某种数字类型
- 必须有 < 运算符定义
- 必须具有 [ ] 访问运算符定义的
- 必须有复制构造函数和赋值运算符
我的想法:
我认为它可能与数字类型不同,但需要明确定义运算符 + 和 /。
第 2 点似乎不正确,因为 < 与 / 和 + 运算符
与第 3 点和第 4 点相同。
虽然我不确定我上面的推理。
解决方案
- 否 - 例如,它可以与数字类型进行隐式转换并已
operator+=
定义。 - 否 - 该运算符未用于
T
- 否 - 该运算符未在 a 上使用
T
,只有 aT*
和指针类型都定义了该运算符。 - 否 - 复制构造函数可以是
delete
d 并且问题是“和”,所以答案是否定的。不过,它需要某种赋值运算符。
考虑这门课,特别是为了能够对尽可能多的问题回答“否”:
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
};
它可以与函数模板一起正常工作:
int main() {
foo arr[2];
auto x = average(arr, 2);
}
推荐阅读
- perforce - Perforce Helix4Git 无法在没有权限的客户端中映射图形存储库
- angular - 如何在信息亭模式下运行 Angular 应用程序?
- javascript - 网格中的 w2ui 文本选择
- vue.js - VueX 等待突变执行
- java - 我想加入 2 个表并获取 table1 的数据并映射到表 1 实体
- jenkins - Jenkins 管道中的开关返回 null,普通 Groovy 中的相同开关返回预期输出
- javascript - react-testing-library - 屏幕与渲染查询
- c# - 如何在 MSTest 中强制将测试状态设置为“通过”?
- android - io.flutter.embedding.android.FlutterView 与 io.flutter.view.FlutterView
- amazon-cloudformation - AWS CloudFormation CLI - 参数问题