c++ - Boost.Fusion 运行时开关

标签 c++ metaprogramming boost-fusion

我正在从文件中读取对象的类型:

enum class type_index { ... };
type_index typeidx = read(file_handle, type_index{});

根据类型索引,我想创建一个类型(从可能的类型列表中),并用它做一些通用的事情(每种类型的通用代码相同):

std::tuple<type1, type2, ..., typeN> possible_types;

boost::fusion::for_each(possible_types, [&](auto i) {
  if (i::typeidx != typeidx) { return; }
  // do generic stuff with i
});

即:

  • 我对不同类型有相同的通用代码,
  • 我希望编译器为每种类型生成特定的代码,
  • 我只知道运行时需要哪种类型,并且
  • 我只想执行该单一类型的代码。

这感觉就像一个带有运行时条件的 switch 语句,但其中的“案例”是在编译时生成的。特别是,这根本不像 for_each 语句(我没有对 vector 、元组、列表中的所有元素做任何事情,而只是对单个元素做任何事情)。

有没有更好更清晰的方式来表达/编写这个成语? (例如,对可能的类型使用 mpl::vector 而不是 std::tuple,使用不同于 for_each 算法的东西。 ..)

最佳答案

我喜欢我惯用的继承 lambdas 技巧:

我以前写过这个

我相信我已经看到 Sumant Tambe 在他最近的 cpptruths.com 帖子中使用它。


演示

这里是一个演示。稍后会添加一些解释。

应用的最重要的技巧是我使用 boost::variant 为我们隐藏类型代码 denum。但即使您保留自己的类型区分逻辑(只需要更多编码),该原则也适用

Live On Coliru

#include <boost/serialization/variant.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

#include <fstream>
#include <iostream>

using namespace boost; // brevity

//////////////////
// This is the utility part that I had created in earlier answers:
namespace util {
    template<typename T, class...Fs> struct visitor_t;

    template<typename T, class F1, class...Fs>
    struct visitor_t<T, F1, Fs...> : F1, visitor_t<T, Fs...>::type {
        typedef visitor_t type;
        visitor_t(F1 head, Fs...tail) : F1(head), visitor_t<T, Fs...>::type(tail...) {}

        using F1::operator();
        using visitor_t<T, Fs...>::type::operator();
    };

    template<typename T, class F> struct visitor_t<T, F> : F, boost::static_visitor<T> {
        typedef visitor_t type;
        visitor_t(F f) : F(f) {}
        using F::operator();
    };

    template<typename T=void, class...Fs>
    typename visitor_t<T, Fs...>::type make_visitor(Fs...x) { return {x...}; }
}

using util::make_visitor;

namespace my_types {
    //////////////////
    // fake types for demo only
    struct A1 {
        std::string data;
    };

    struct A2 {
        double data;
    };

    struct A3 {
        std::vector<int> data;
    };

    // some operations defined on A1,A2...
    template <typename A> static inline void serialize(A& ar, A1& a, unsigned) { ar & a.data; } // using boost serialization for brevity
    template <typename A> static inline void serialize(A& ar, A2& a, unsigned) { ar & a.data; } // using boost serialization for brevity
    template <typename A> static inline void serialize(A& ar, A3& a, unsigned) { ar & a.data; } // using boost serialization for brevity

    static inline void display(std::ostream& os, A3 const& a3) { os << "display A3: " << a3.data.size() << " elements\n"; }
    template <typename T> static inline void display(std::ostream& os, T const& an) { os << "display A1 or A2: " << an.data << "\n"; }

    //////////////////
    // our variant logic
    using AnyA = variant<A1,A2,A3>;

    //////////////////
    // test data setup
    AnyA generate() { // generate a random A1,A2...
        switch (rand()%3) {
            case 0: return A1{ "data is a string here" };
            case 1: return A2{ 42 };
            case 2: return A3{ { 1,2,3,4,5,6,7,8,9,10 } };
            default: throw std::invalid_argument("rand");
        }
    }

}

using my_types::AnyA;

void write_archive(std::string const& fname) // write a test archive of 10 random AnyA
{
    std::vector<AnyA> As;
    std::generate_n(back_inserter(As), 10, my_types::generate);

    std::ofstream ofs(fname, std::ios::binary);
    archive::text_oarchive oa(ofs);

    oa << As;
}

//////////////////
// logic under test
template <typename F>
void process_archive(std::string const& fname, F process) // reads a archive of AnyA and calls the processing function on it
{
    std::ifstream ifs(fname, std::ios::binary);
    archive::text_iarchive ia(ifs);

    std::vector<AnyA> As;
    ia >> As;

    for(auto& a : As)
        apply_visitor(process, a);
}

int main() {
    srand(time(0));

    write_archive("archive.txt");

    // the following is c++11/c++1y lambda shorthand for entirely compiletime
    // generated code for the specific type(s) received
    auto visitor = make_visitor(
        [](my_types::A2& a3) { 
                std::cout << "Skipping A2 items, just because we can\n";
                display(std::cout, a3);
            },
        [](auto& other) { 
                std::cout << "Processing (other)\n";
                display(std::cout, other);
            }
        );

    process_archive("archive.txt", visitor);
}

打印

Processing (other)
display A3: 10 elements
Skipping A2 items, just because we can
display A1 or A2: 42
Processing (other)
display A1 or A2: data is a string here
Processing (other)
display A3: 10 elements
Processing (other)
display A1 or A2: data is a string here
Processing (other)
display A1 or A2: data is a string here
Processing (other)
display A3: 10 elements
Processing (other)
display A1 or A2: data is a string here
Processing (other)
display A3: 10 elements
Processing (other)
display A3: 10 elements

关于c++ - Boost.Fusion 运行时开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26846299/

相关文章:

c++ - 我怎样才能使 std::find_if 和 std::map 使用一些 boost 库协同工作?

C++:使用互斥量和条件变量控制线程执行顺序

c++ - 结构 ifreq : different definition in "linux/if.h" and man page

c++ - 当 VISUAL_ID 和 screen->root_visual 不相等时,glXCreateWindow 不起作用

python - 确定描述符中的短运算符(+= like)用法

c++ - 填充 std::tuple

c++ - ScrollWheel 没有生成任何事件 - GLUT

c++ - C++ 中编译时生成的 block

Groovy MetaProgramming - 拦截所有方法,甚至丢失的方法

boost - boost::MPL 和 boost::fusion 之间的区别