问题描述
今天,我正在尝试在编译时创建一个特定的元组(至少对我来说).
Today I'm trying to create a tuple a little specific (for me at least) and at compile time.
我有一些基本的结构,可以说:
I have some basic struct, let say :
struct Foo1 { int data; };
struct Foo2 { int data; };
struct Foo3 { int data; };
另一个结构,但有一些模板内容:
And another struct but with some template stuff :
template < typename T,
size_t Size >
struct Metadata {
using type = T;
std::bitset<Size> bitset;
};
所以现在我想创建这种元组:
So now I want to create this kind of tuple :
constexpr std::tuple<Metadata<Foo1, 3>, Metadata<Foo2, 3>, Metadata<Foo3, 3>> test { {0}, {0}, {0}};
但是以一种自动方式,更像是:
But in an automatic way, more like:
template < typename ... Ts >
constexpr auto make_metadata() {
return std::tuple<Metadata<Foo1, sizeof...(Ts)>,
Metadata<Foo2, sizeof...(Ts)>,
Metadata<Foo3, sizeof...(Ts)>>{{0},{0},{0}};
}
最后一个代码远不是很好,所以我想拥有类似的功能,但是却是自动的.也许带有tuple_cat和fold表达式,但是我有点迷失了.因此,如果有人知道答案:)
Well the last code is far from good, so I'd like to have something like that but automatic. Maybe with tuple_cat and fold expression, but I'm a little lost. So if somebody know the answer :)
推荐答案
您可以使用...
在单个表达式中表示多个内容.在这种情况下,您想立即展开Ts
并立即展开:
You can use ...
to mean multiple things in a single expression. In this case, you want to expand Ts
both immediately and non-immediately:
template <class... Ts>
constexpr auto make_metadata()
{
return std::make_tuple(Metadata<Ts, sizeof...(Ts)>{0}...);
}
此外,如果让您更清楚地以这种方式编写内容,则您不必将所有内容都写在一行上.
Also, you don't have to write everything on a single line if it makes it clearer for you to write it this way:
template <class... Ts>
constexpr auto make_metadata()
{
constexpr size_t N = sizeof...(Ts);
return std::make_tuple(Metadata<Ts, N>{0}...);
}
这篇关于创建具有可变类型的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!