Using fields stored in variadic data structure as method arguments

  • A+
Category:Languages

I have a variadic data structure, each "layer" containing one field.

How can use all the fields stored in the structure as arguments to a function or a constructor?

template <class... Ts> class Builder {};  template <class T, class... Ts> class Builder<T, Ts...> : public Builder<Ts...> { public:     Builder(T t, Ts... ts) : Builder<Ts...>(ts...), tail(t) {}      Result build() {       // want to use tail, Builder<Ts...>::tail, etc.       // as ctor or function arguments without multiple specializations     }  private:     const T tail; }; 

In general, I want to be capable of doing something like this:

Builder<int, string, int> b1{10, "aaa", 20}; Result r1 = b1.build(); // should invoke Result's constructor (int, string, int)  Builder<int> b2{10}; Result r2 = b2.build(); // should invoke Result's constructor (int) 

 


If you don't want to use tuple as a member to hold the values, you could do it this way:

template <class... Ts> class Builder {   protected:   template<class...Us>   Result do_build(const Us&...us){     return Result(us...);     }   };  template <class T, class... Ts> class Builder<T, Ts...> : public Builder<Ts...> { public:     Builder(T t, Ts... ts) : Builder<Ts...>(ts...), tail(t) {}      Result build() {       return do_build();     } protected:   template<class...Us>   Result do_build(const Us&...us){     return Builder<Ts...>::do_build(us...,tail);     } private:     const T tail; }; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: