gpt4 book ai didi

c++ - 连接元组作为类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:17:59 25 4
gpt4 key购买 nike

我正在尝试练习一些模板编程。也许有一个标准的方法来做到这一点,我会很感激这样的答案,但我的主要目标是练习模板编程技术,所以我尝试自己实现它:

我需要连接多个元组,但作为类型,不像 std::cat_tuple可以。所以我需要类似 cat<std::tuple<int, float>, std::tuple<char, bool>, ...> 的东西得到std::tuple<int, float, char, bool, ...>作为一种类型。

我当前的尝试失败了 is not a template错误:

/* Concat tuples as types: */
template <typename first_t, typename... rest_t> struct cat {
using type = typename _cat<first_t, typename cat<rest_t...>::type>::type;
^^^^ cat is not a template
};
template <typename first_t, typename second_t>
struct cat<first_t, second_t> {
using type = typename _cat<first_t, second_t>::type;
^^^^ cat is not a template
};
// Concat two tuples:
template <typename, typename> struct _cat;
template <typename tuple_t, typename first_t, typename... rest_t>
struct _cat<tuple_t, std::tuple<first_t, rest_t...>> {
using type = typename _cat<typename append<first_t, tuple_t>::type, std::tuple<rest_t...>>::type;
};
template <typename tuple_t, typename first_t>
struct _cat<tuple_t, std::tuple<first_t>> {
using type = typename append<first_t, tuple_t>::type;
};
// Prepend element to tuple:
template <typename, typename> struct prepend;
template <typename elem_t, typename... tuple_elem_t>
struct prepend<elem_t, std::tuple<tuple_elem_t...>> {
using type = std::tuple<elem_t, tuple_elem_t...>;
};
// Apppend element to tuple:
template <typename, typename> struct append;
template <typename elem_t, typename... tuple_elem_t>
struct append<elem_t, std::tuple<tuple_elem_t...>> {
using type = std::tuple<tuple_elem_t..., elem_t>;
};

可能导致错误的原因是什么?

这是一个好方法吗?它可能会以更简单的方式解决,但我希望它是多用途的(使用追加/前置操作等)。

最佳答案

单行直接模板别名怎么样:

template<typename ... input_t>
using tuple_cat_t=
decltype(std::tuple_cat(
std::declval<input_t>()...
));


tuple_cat_t<
std::tuple<int,float>,
std::tuple<int>
> test{1,1.0f,2};

关于c++ - 连接元组作为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53394100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com