Boost logo

Boost :

Subject: Re: [boost] task_array<n> and variadic templates
From: Yechezkel Mett (ymett.on.boost_at_[hidden])
Date: 2008-11-19 10:51:31


On Wed, Nov 19, 2008 at 5:32 PM, Yechezkel Mett
<ymett.on.boost_at_[hidden]> wrote:
> On Wed, Nov 19, 2008 at 5:08 PM, Vicente Botet <vicente.botet_at_[hidden]> wrote:
>>
>> Comming back to my example, I need to store the tasks on an array. I do it now like this:
>>
>> template <>
>> struct task_array<3> {
>> task arr_[3];
>> template <typename F_1, typename F_2, typename F_3>
>> task_array(F_1 f1, F_2 f2, F_3 f3) {
>> arr_[0]=task(f1);
>> arr_[1]=task(f2);
>> arr_[2]=task(f3);
>> }
>> };
>>
>>
>> I don't see a simple way to do it with variadic templates other than recursion.
>>
>> Is there a simple way to achieve this something like
>>
>> template <std::size N>
>> struct task_array {
>> task arr_[N];
>> template <typename... F>
>> task_array(F... f) {
>> static_assert(sizeof...(T) == N, "Constructor must provide N parameters")
>> {
>> arr_={task(f)...};
>> }
>> };
>
> Recursion is the way to do anything with variadic templates :-)
> But the following should work in theory:
>
> template <std::size N>
> struct task_array {
> task arr_[N];
> template <typename... F>
> task_array(F... f)
> : arr_({task(f)...})
> {
> static_assert(sizeof...(T) == N, "Constructor must provide N parameters")
> }
> };
>
> if you can find a compiler that supports the new initialisation syntax, that is.

On a current compiler:

template <std::size N>
struct task_array {
 task arr_[N];
 template <typename... F>
  task_array(F... f) {
      static_assert(sizeof...(T) == N, "Constructor must provide N parameters")
      boost::array<task, N> arr = { task(f)... };
      std::copy(arr.begin(), arr.end(), arr_);
  }
};

if you don't mind the multiple copies -- perhaps better to move rather
than copy.

Recursion isn't too bad either:

namespace detail
{
 template<typename T, typename Head, typename... Tail>
  void fill_array(T* arr, Head h, Tail... t) {
      *arr = T(h);
      fill_array(arr + 1, t...);
  }

 template<typename T>
  void fill_array(T* arr) {}
}

template <std::size N>
struct task_array {
 task arr_[N];
 template <typename... F>
  task_array(F... f) {
      static_assert(sizeof...(T) == N, "Constructor must provide N parameters")
      detail::fill_array(arr_, f...);
  }
};

Yechezkel Mett


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk