Variadic templates and switch statement?

后端 未结 5 1351
栀梦
栀梦 2020-12-24 13:42

I have the following function which can take N arguments of different types, and forwards them to N functions templated on each individual type, in this manner (example with

5条回答
  •  清歌不尽
    2020-12-24 14:12

    Also for fun, this might be a bit too convoluted

    #include
    #include
    
    template
    void g(T&& t)
    {
        // This function gets called
    }
    
    template
    void entry(void* p)
    {
        g(*(std::remove_reference_t*)p);
    }
    
    template
    using table_t = std::array;
    
    template
    constexpr auto make_table()
    {
        return table_t{
            entry...
        };
    }
    
    template
    void f_(const table_t&, int)
    {
    
    }
    
    template
    void f_(const table_t& table, int select, T&& t, Ts&&... ts)
    {
        if(select == N - sizeof...(Ts) - 1)
            table[select]((void*)&t);
        else
            f_(table, select, std::forward(ts)...);
    }
    
    template
    void f(int select, Ts&&... ts)
    {
        static constexpr auto table = make_table();
        if(select < 0 || select >= int(sizeof...(Ts)))
            throw "out of bounds";
        f_(table, select, std::forward(ts)...);
    }
    

    Which rolls a vtable in f and dispatches accordingly to g.

    Live

提交回复
热议问题