本文介绍了为什么std :: visit采用可变数量的变体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试更加熟悉C ++ 17,我刚刚注意到 std::visit :

Trying to get more familiar with C++17, I've just noticed std::visit:

template <class Visitor, class... Variants>
constexpr /*something*/ visit(Visitor&& vis, Variants&&... vars);

为什么std::visit不采用单个变体,而是采用任意数量的变体?我的意思是,您始终可以使用一些标准库函数,并让其以相同的角色使用多个参数,并对所有参数进行处理(例如,容器中多个元素的std::find());否则您可能会吸引多个访客,并在同一个变体上使用他们.

Why does std::visit not take a single variant, but rather any number of variants? I mean, you can always take some standard library function and have it take multiple parameters with the same role, working on all of them (e.g. std::find() for multiple elements in a container); or you could be taking multiple visitors and using them on the same variant.

那么,为什么要进行这种特定的变异化"?

So, why this specific 'variadification'?

推荐答案

因为我们需要允许访问变体内类的组合.也就是说,如果我们有

Because we need to allow for visitation of combinations of classes within variants. That is, if we have

using Var1 = std::variant<A,B>;
using Var2 = std::variant<C,D>;

我们显然可以使用以下类型的访客:

we can obviously use these kinds of visitors:

struct Visitor1 {
    void operator()(A);
    void operator()(B);
};

struct Visitor2 {
    void operator()(C);
    void operator()(D);
};

分别带有Var1Var2.我们甚至可以单独使用Var1Var2来使用这种第二种类型:

with Var1 and Var2 respectively. We can even use this next kind, with both Var1 and Var2 individually:

struct Visitor3 {
    void operator()(A);
    void operator()(B);
    void operator()(C);
    void operator()(D);
};

但是缺少的OP是我们希望能够访问四对(A,C)(A,D)(B,C)(B,D)中的一个-在查看一对Var1一起.这就是为什么std::visit的可变参数是必需的.合适的访客如下所示:

but what OP is missing is that we want to be able to visit one of the four pairs (A,C), (A,D), (B,C), (B,D) - when looking at a pair of Var1 and Var2 together. That's why the variadic argument to std::visit is all-but-necessary. An appropriate visitor would look like this:

struct Visitor4 {
    void operator()(A,C);
    void operator()(A,D);
    void operator()(B,C);
    void operator()(B,D);
};

,我们将呼叫std::visit(Visitor4{}, my_var1_instance, my_var2_instance);

这篇关于为什么std :: visit采用可变数量的变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 13:56