【发布时间】:2020-06-02 15:37:27
【问题描述】:
我正在尝试实现一种从元组中删除某些类型的方法;例如,我希望能够例如根据条件,只取一个元组的前 2 个模板参数的元组:
- 是否可以将元组包含的类型“打包”回参数包中? (元组 -> 类型名...包含类型)
- 是否可以组合一个参数。带有类型名的包(例如,使用“Pack1...,Pack2...”为结构指定单个参数包?
#include <cstdint>
#include <tuple>
template <typename... tpl> struct Helper {
template <std::size_t rem, typename curr, typename... rest> struct take {
using type = Helper<(tpl..., curr)>::take<rem-1, rest...>::type; // here, I'm trying (2.)
};
template <typename curr, typename... rest> struct take<0, curr, rest...> {
using type = std::tuple<tpl...>;
};
};
template <std::size_t s, typename... tpl> using take_t = Helper<>::take<s, tpl...>;
int main() {
take_t<2, int, int, int> k = std::make_tuple(1, 2);
}
edit line Helper 失败并显示以下消息:
/home/juli/test.cc:6:18: error: need ‘typename’ before ‘Helper<tpl ..., curr>::take’ because ‘Helper<tpl ..., curr>’ is a dependent scope
6 | using type = Helper<tpl..., curr>::take<rem-1, rest...>::type;
当我提供类型名时
/home/juli/test.cc:6:53: error: expected ‘;’ before ‘<’ token
6 | using type = typename Helper<tpl..., curr>::take<rem-1, rest...>::type;
edit2 我通过 [辅助函数](https://gist.github.com/juliusHuelsmann/669f537aeb5e7105386d510d186b24e1 ),但是当构造函数不是 constexpr 时,那些非原始类型会失败,所以我不能在我的用例中使用它,并且很想知道如何实现这一点以及我的方法失败的原因。
【问题讨论】:
-
不能贡献,但出于好奇... 是什么意思?我知道它是可变参数,但为什么 typename... tpl 而不是 typename tpl, ... ?
-
@StefanoBorini 见:en.cppreference.com/w/cpp/language/parameter_pack
-
所以你想取一个
std::tuple<int, double, long>并得到一个std::tuple<int, double>吗? -
Helper<tpl..., curr>出了什么问题?
标签: c++ tuples template-meta-programming parameter-pack