【发布时间】:2020-03-20 15:46:56
【问题描述】:
我有一个包含变体类的 std::vector。我想用相同的数据构造一个元组。这可能吗?元组的正常构造方法似乎很受限制。
//In reality, I'm using JUCE::var.
// SimpleVariant is here just to make the example code more explicit.
struct SimpleVariant
{
SimpleVariant(int i) : a(i), b("") {}
SimpleVariant(const std::string& s) : a(0), b(s) {}
operator int() const { return a; }
operator std::string() const { return b; }
private:
int a;
std::string b;
};
template <typename... T>
struct VariantTuple
{
VariantTuple(const std::vector<SimpleVariant>& v)
{
// how do I initialize the tuple here?
}
private:
std::tuple<T...> tuple;
};
std::vector<SimpleVariant> v{ SimpleVariant(1),
SimpleVariant(2),
SimpleVariant("a") };
VariantTuple<int, int, std::string> t (v);
基于 cmets 的一些说明:
我不需要元组来逐项匹配数组,或者从给定数组中推断出类型。我想取一个给定的数组,然后提取与某种类型匹配的变体。因此,例如,给定上述数组v,我希望能够构造一个VariantTuple<int, std::string>,并让它匹配术语“1”和“a”。这引入了许多其他问题,超出了我原来问题的范围。但是我现在感兴趣的问题是,是否有可能首先基于数组构造一个元组。
【问题讨论】:
-
题名提到了数组,但题测试和示例使用
vectors。你问的是哪个? -
如果将结果元组作为函数参数而不是直接返回值给出,这将是可能的,但它需要编译所有可能的类型排列,这很快就会在变量大小和向量长度上爆炸.
-
@chris 您需要设置向量大小的上限以编译每个可能生成的元组。这不是很实用。不过你可以用
std::array做到这一点。 -
@FrançoisAndrieux,对,它对于低长度是可行的,而且编译时间对于更高的长度来说真的很糟糕。
-
您实际上是在使用
SimpleVariant还是只是一个例子?你可以改用std::variant吗?SimpleVariant看起来非常难以用作variant,并且会使您尝试使用它做的任何事情变得更加复杂。