元组和汇总
Tuple and summaring
本文关键字:元组 更新时间:2023-10-16
如何编写一个函数来检查是否可以汇总所有元组元素
template <size_t ID, class T>
int check(const T& p)
{
size_t n = std::tuple_size_v<T>;
auto sum = std::get<0>(p);
if constexpr (ID < std::tuple_size_v<T>) {
if (sum += std::get<ID>(p)) {
check<ID + 1>(p);
}
else
...
可以使用部分特化和折叠表达式来检查对于std::tuple<T1, T2, T3>
,是否可以调用T1{} + T2{} + T3{}
;
#include <tuple>
#include <iostream>
#include <string>
template <typename Tuple, typename = void>
struct check_impl : public std::false_type {};
template <typename... Ts>
struct check_impl<std::tuple<Ts...>, std::void_t<decltype((std::declval<Ts>() + ...))>> : public std::true_type {};
template <typename Tuple>
constexpr bool check = check_impl<Tuple>::value;
int main() {
std::cout << check<std::tuple<int, double, char>> << " " << check<std::tuple<int, std::string>>;
}
实现相同且更有效结果的替代方法:
#include <tuple>
#include <iostream>
#include <string>
template <typename... Ts>
constexpr auto check_impl(...) noexcept -> bool { return false; }
template <typename... Ts>
constexpr auto check_impl(int) noexcept -> decltype((std::declval<Ts>() + ...), bool{}) {
return true;
}
template <typename... Ts>
constexpr bool check(std::tuple<Ts...>) noexcept {
return check_impl<Ts...>(0);
}
int main() {
std::cout << check(std::tuple<int, double, char>{}) << ' ' << check(std::tuple<int, std::string>{});
}
相关文章:
- C++:TypeDef使用元组
- Pybind11:将元组列表从Python传递到C++
- 重载元组索引运算符-C++
- 在C++中,如何通过几种类型从元组中选择多个元素
- 将fold表达式与std::一起用于两个元组
- std::ranges::elements_view,用于自定义类似元组的数据
- 将元组的向量转换/构造为堆
- 专用于 std 元组的模板,而无需用户执行remove_cvref
- 将元组的向量构造成堆
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 将元组类型扩展为可变参数模板?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 类内部和外部静态 constexpr 元组之间的差异
- 可变参数模板与使用元组在参数中添加不同的数据对
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- boost::包含提升单元的元组的哈希值
- 我正在寻找一种优雅的方式来从元组向量创建tuple_element向量
- 如何在可变参数模板函数中遍历可变参数元组?
- 如何使用 SML 随机生成八进制元组
- 元组的运行时索引