使用额外的参数提升变体访客 [英] Boost variant visitor with an extra parameter

查看:68
本文介绍了使用额外的参数提升变体访客的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码与下面类似.

typedef uint32_t IntType;
typedef IntType IntValue;
typedef boost::variant<IntValue, std::string>  MsgValue;

MsgValue v;

与其说这个,

IntValue value = boost::apply_visitor(d_string_int_visitor(), v);

我想传递一个这样的额外参数:但是operator()给出了编译错误.

I would like to pass an extra parameter like this: But operator() gives a compile error.

//This gives an error since the overload below doesn't work.
IntValue value = boost::apply_visitor(d_string_int_visitor(), v, anotherStr);

class d_string_int_visitor : public boost::static_visitor<IntType>
{
public:
    inline IntType operator()(IntType i) const
    {
        return i;
    }

    inline IntValue operator()(const std::string& str) const noexcept
    {
        // code in here
    }

    //I want this, but compiler error.
    inline IntValue operator()(const std::string& str, const std::string s) const noexcept
    {
        // code in here
    }
};

推荐答案

您可以使用

You can bind the extra string argument to the visitor using std::bind. First, add the std::string parameter to all of the visitor's operator() overloads.

class d_string_int_visitor : public boost::static_visitor<IntType>
{
public:
    inline IntType operator()(IntType i, const std::string& s) const
    {
        return i;
    }

    inline IntValue operator()(const std::string& str, const std::string& s) const noexcept
    {
        // code in here
        return 0;
    }
};

现在创建一个您已经将第二个 string 参数绑定到的访问者.

Now create a visitor to which you have bound the second string argument.

auto bound_visitor = std::bind(d_string_int_visitor(), std::placeholders::_1, "Hello World!");
boost::apply_visitor(bound_visitor, v);

实时演示

但是,更好的解决方案是将字符串作为访问者的构造函数参数传递.

However, a better solution would be to pass the string as the visitor's constructor argument.

这篇关于使用额外的参数提升变体访客的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆