Generating one class member per variadic template argument

后端 未结 5 1683
后悔当初
后悔当初 2020-12-02 14:52

I have a template class where each template argument stands for one type of value the internal computation can handle. Templates (instead of function overloading) are needed

5条回答
  •  被撕碎了的回忆
    2020-12-02 15:03

    One way to do such a thing, as mentioned in πάντα-ῥεῖ's comment is to use a tuple. What he didn't explain (probably to save you from yourself) is how that might look.

    Here is an example:

    using namespace std;
    
    // define the abomination    
    template
    struct thing
    {
        thing(std::vector... args)
        : _x { std::move(args)... }
        {}
    
        void print()
        {
            do_print_vectors(std::index_sequence_for());
        }
    
    private:
        template
        void do_print_vectors(std::index_sequence)
        {
            using swallow = int[];
            (void)swallow{0, (print_one(std::get(_x)), 0)...};
        }
    
        template
        void print_one(const Vector& v)
        {
            copy(begin(v), end(v), ostream_iterator(cout, ","));
            cout << endl;
        }
    
    private:
        tuple...> _x;
    };
    
    
    // test it
    BOOST_AUTO_TEST_CASE(play_tuples)
    {
        thing t {
            { 1, 2, 3, },
            { 1.1, 2.2, 3.3 },
            { "one"s, "two"s, "three"s }
        };
    
        t.print();
    }
    

    expected output:

    1,2,3,
    1.1,2.2,3.3,
    one,two,three,
    

提交回复
热议问题