Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to store variadic function template arguments into a union vector?

I have a simple union whose constructor stores its argument in the relevant member:

union Data
{
    Data(int    i) : _i(i) { }
    Data(double d) : _d(d) { }
    Data(char   c) : _c(c) { }

    int    _i;
    double _d;
    char   _c;
};

I then have a variadic constructor which takes arguments of these types and stores them in a vector of the union using template recursion:

template<typename... Ts>
DataStore(Ts... ts)
{
    _data.reserve(sizeof...(ts));
    store(ts...);
}

template<typename T, typename... Ts>
void store(T t, Ts... ts)
{
    _data.push_back(t);
    store(ts...);
}

void store()
{
    // terminal condition
}

This will result in a series of vector::push_back calls matching the number of arguments.

Is this the most efficient/fastest way to populate the union vector?

Are there any tricks (can be specific to x86-64 / Linux) I can employ to make this faster?

Working example:

#include <iostream>
#include <vector>

union Data
{
    Data(int    i) : _i(i) { }
    Data(double d) : _d(d) { }
    Data(char   c) : _c(c) { }

    int    _i;
    double _d;
    char   _c;
};

struct DataStore
{
    template<typename... Ts>
    DataStore(Ts... ts)
    {
        _data.reserve(sizeof...(ts));
        store(ts...);
    }

    template<typename T, typename... Ts>
    void store(T t, Ts... ts)
    {
        _data.push_back(t);
        store(ts...);
    }

    void store()
    {
        // terminal condition
    }

    std::vector<Data> _data;
};

int main()
{
    DataStore d(1, 2.3, 'c');

    std::cout << d._data.size() << '\n'
              << d._data[0]._i  << '\n'
              << d._data[1]._d  << '\n'
              << d._data[2]._c  << '\n';

    return 0;
}
like image 959
Steve Lorimer Avatar asked Feb 16 '26 01:02

Steve Lorimer


1 Answers

You can initialize _data directly.

template<typename... Ts>
DataStore(Ts... ts) : _data{ts...}
{}
like image 118
Miles Budnek Avatar answered Feb 17 '26 14:02

Miles Budnek