c++ - boost::static_visitor 中 operator() 的附加参数

标签 c++ performance boost c++14 variant

我必须创建 boost::variant 对象并使用 static_visitor。 不幸的是我需要额外的参数......

哪种解决方案更好? 要将此对象作为类的字段,当我想使用访问者时,我必须创建实例:

class Visitor : public boost::static_visitor<>
{
public:
    Visitor(int extra): extra{extra} {}
    void operator()(const T1&) { /* ... */}
    void operator()(const T2&) { /* ... */}

private:
    int extra;
};

并在每次我想使用它时创建 Visitor 对象:

Visitor visitor(x);
boost::apply_visitor(visitor, t);

或者使用 boost::bind 并创建 Visitor 一次并使用 boost::bind

class Visitor : public boost::static_visitor<>
{
public:
    void operator()(const T1&, int extra) { /* ... */ }
    void operator()(const T2&, int extra) { /* ... */ }
};

用法:

auto visitor = std::bind(SctpManager::Visitor(), std::placeholders::_1, extra);
boost::apply_visitor(visitor, t);

什么是更好(更快、更优雅)的解决方案?

或者有什么更好的解决方案吗?

最佳答案

没有比本质上更优雅的方式了。您可以使用 lambda(如果您的编译器/boost 版本足够现代)。

“低技术”选项是使用保存状态的结构(第 3 个示例):

Live On Coliru

#include <boost/variant.hpp>
#include <iostream>

struct T1{};
struct T2{};

struct Visitor : boost::static_visitor<>
{
    void operator()(T1 const&, int extra) const { std::cout << __PRETTY_FUNCTION__ << " extra:" << extra << "\n"; }
    void operator()(T2 const&, int extra) const { std::cout << __PRETTY_FUNCTION__ << " extra:" << extra << "\n"; }
};

int main() {
    boost::variant<T1, T2> tests[] = { T1{}, T2{} };

    {
        Visitor vis;
        for (auto v: tests)
            apply_visitor([=](auto const& v) { vis(v, 42); }, v);
    }

    {
        auto vis = [vis=Visitor{}](auto const& v) { vis(v, 1); };
        for (auto v: tests)
            apply_visitor(vis, v);
    }


    {
        struct {
            using result_type = void;
            int extra;
            void operator()(T1 const&) const { std::cout << __PRETTY_FUNCTION__ << " extra:" << extra << "\n"; }
            void operator()(T2 const&) const { std::cout << __PRETTY_FUNCTION__ << " extra:" << extra << "\n"; }
        } vis { 99 };

        for (auto v: tests)
            apply_visitor(vis, v);
    }
}

打印

void Visitor::operator()(const T1&, int) const extra:42
void Visitor::operator()(const T2&, int) const extra:42
void Visitor::operator()(const T1&, int) const extra:1
void Visitor::operator()(const T2&, int) const extra:1
void main()::<unnamed struct>::operator()(const T1&) const extra:99
void main()::<unnamed struct>::operator()(const T2&) const extra:99

关于c++ - boost::static_visitor 中 operator() 的附加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46119362/

相关文章:

JavaScript、Ajax : How to visualize Boomerang. js 结果?

c++ - 仅在 Boost.Spirit.Qi 语法初始化的优化构建中出现段错误

C++ - 将类传递给其他类。我如何知道何时使用友元继承

c# - 在 C# 中使用 C++ dll 对象

c++ - 如何通过类成员函数作为模板参数?

c++ - Arduino Mega 上的奇怪计算

performance - F# 代码引用调用、性能和运行时要求

mysql - 在 MySQL 中为连接某个表创建索引

c++ - boost::asio 无法从文件中读取超过 65536 个字节

c++ - 如何重命名 boost 属性树中的节点/元素?