c++ - 从数组构建可变元组以返回
问题描述
我想要一种方法来构建一个具有变量编号或条目的元组,该元组基于对象在成员变量容器(例如向量)中有多少条目。
这是我最好的结果。但是,不工作。我显然在返回值构造中遗漏了一些东西。假设m_values
是一个容器,其中包含我想放入元组并返回的值。
template<typename... T>
std::tuple<T...> getValuesTuple()
{
if (m_values[0].isValid())
{
return buildReturnTuple(0);
}
return std::tuple<T...>();
}
template<typename... T>
std::tuple<T...> buildReturnTuple(size_t i)
{
if (i + 1 < MAX_VALUES && m_values[i + 1].isValid())
{
return std::tuple<T, T...>(m_values[i], buildReturnTuple(i + 1));
}
return std::tuple<T...>(m_values[i]...);
}
先感谢您!
解决方案
如果您在编译时知道数组的大小,可以通过以下方式完成:
#include <array>
#include <tuple>
#include <utility>
struct MyType {};
constexpr auto my_type_to_any_other_type(const MyType&) {
// use if constexpr to return desired types
return 0;
}
template<std::size_t N, std::size_t... Idx>
constexpr auto array_to_tuple_helper(const std::array<MyType, N>& a, std::index_sequence<Idx...>) {
return std::make_tuple(my_type_to_any_other_type(a[Idx])...);
}
template<std::size_t N>
constexpr auto array_to_tuple(const std::array<MyType, N>& a) {
return array_to_tuple_helper(a, std::make_index_sequence<N>{});
}
int main () {
auto t = array_to_tuple(std::array<MyType, 1>{ MyType{} });
return 0;
}
推荐阅读
- reactjs - 在第一次 api 调用返回数据后进行第二次 api 调用
- python - 试图复制带有扩展名的文件,shutil 问题
- html - CSS 在我的 Python/HTML 项目中不起作用
- flutter - ThemeData primarySwatch 属性不能使用我的自定义 MaterialColor
- php - whereBetween issue,返回错误记录
- python - 提取最常用的词作为 WordCloud 清理?
- python-3.x - 为什么我的 BP 神经网络的准确率太低?
- php - Laravel:无法访问中间件中的资源集合
- r - 为什么我的 stringr 函数在我的数据集中途失败?
- visual-studio - 表格模型部署失败