区分添加剂类型
Differentiating additive types?
我在泛型编程中的第一步包括编写一个简单的函数,该函数累积作为其参数传递的向量的总和。问题是该函数应该只适用于具有有意义的求和值的类型。
代码很简单:
template <typename T>
T accumulate_sum (const std::vector<T>& v) {
// check for type and decide whether to sum or return nothing
T sum = v[0];
for (size_t i = 1; i < v.size(); ++i) sum += v[i];
return sum;
}
问题是如何区分添加剂类型?
模板函数在其模板参数上强加一个隐式接口。如果您的类型 T
没有operator+=
,则会收到编译器错误。
#include <cstddef>
#include <vector>
using namespace std;
template <typename T>
T accumulate_sum (const std::vector<T>& v) {
// check for type and decide whether to sum or return nothing
T sum = v[0];
for (size_t i = 1; i < v.size(); ++i) sum += v[i];
return sum;
}
struct Test {}; // not additive
int main()
{
std::vector<Test> v { Test{}, Test{} };
accumulate_sum(v);
}
这将给出以下错误消息(实时示例)
main.cpp:10:47: error: no viable overloaded '+=' for (size_t i = 1; i < v.size(); ++i) sum += v[i]; ~~~ ^ ~~~~ main.cpp:19:5: note: in instantiation of function template specialization 'accumulate_sum<Test>' requested here accumulate_sum(v); ^ 1 error generated.
使用概念技术规范,您可以添加语法特征并获得更好的错误消息。您也可以使用static_assert
来执行此操作。
#include <experimental/type_traits>
#include <utility>
template<class T>
using add_inc_t = decltype(std::declval<T&>() += std::declval<T>());
template<class T>
constexpr auto is_additive_v = std::experimental::is_detected_v<add_inc_t, T>;
template <typename T>
T accumulate_sum (const std::vector<T>& v) {
static_assert(is_additive_v<T>, "the type T needs to be additive by providing operator+");
// as before
}
使用 gcc 6.0 SVN 主干的实时示例(尚未发布)。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 区分添加剂类型