Reputation: 13575
For example
void assign(vector<int> const& v, int a, float b)
{
a = v[0];
b = (float)v[1];
}
Here the value types doesn't need to be same. I want to make a function to assign variable number of variables. I can use variadic function. But I think using parameter pack may be more efficient. How to implement it? Thanks!
Upvotes: 3
Views: 71
Reputation: 96791
Fold expressions to the rescue!
template <typename ...P> void assign(const std::vector<int> &v, P &... params)
{
std::size_t index = 0;
(void(params = static_cast<P>(v[index++])) , ...);
}
If if has to be in C++11, you could use the dummy array trick:
template <typename ...P> void assign(const std::vector<int> &v, P &... params)
{
std::size_t index = 0;
using dummy = int[];
(void)dummy{0, (void(params = static_cast<P>(v[index++])), 0) ...};
}
Upvotes: 7