我有一个元组,我想通过一个变量访问元素,我如何才能做到这一点?现在我使用switch case来解决这个问题。如下所示:
unsigned short& indices(unsigned char samecnt) {
switch (samecnt)
{
case 12:
return std::get<12>(view).indices;
case 11:
return std::get<11>(view).indices;
}
}元组是view_rep:
template<unsigned char N>
struct poker_view
{
unsigned short indices = 0;
constexpr static unsigned char count = N;
};
using wilds_view = poker_view<1>;
template<int N, class... Types>
struct poker_view_rep :public poker_view_rep<N - 1, poker_view<N - 1>, Types...> {
};
template<class... Types>
struct poker_view_rep<1, Types...>
{
using type = std::tuple<wilds_view, Types...>;
};
using view_rep = poker_view_rep<13>::type;发布于 2021-01-26 18:03:07
实际上,您不能将非常数表达式用作模板参数,因此您必须通过一些分派将运行时值“转换”为constexpr。switch是另一种选择。
在您的示例中,您可以使用array:
unsigned short& indices(std::index_sequence<Is...>, unsigned char samecnt) {
std::array<unsigned short*, sizeof...(Is)> arr{{&std::get<Is>(view).indices...}};
return *arr[samecnt];
}
unsigned short& indices(std::index_sequence<Is...>, unsigned char samecnt) {
return indices(std::make_index_sequence<13>(), samecnt);
}或使用std::apply
unsigned short& indices(std::index_sequence<Is...>, unsigned char samecnt) {
return std::apply([](auto&... args) -> unsigned short&
{ return std::array{{&args.indices...}}[samecnt]; }, view);
}https://stackoverflow.com/questions/65895435
复制相似问题