元组和汇总

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>{});
}