Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic-templates class constructor

I wrote the following code to create a class with a constructor that takes as arguments a variable number (N) of integer plus two double, as follow:

#include <cstdio>
#include <cstdlib>

#include <vector>
#include <array>

template <std::size_t N>
class point_t {

public:

  std::vector<int> values;

  template<typename ... Args>
  point_t(Args ... args, double distance, double value) {

    std::array<int , N> list = {(args)...};

    for(std::size_t i=0; i<N; ++i) values[i] = list[i];

  }

};


int main(int argc, char *argv[]) {

  point_t<4> test(1, 2, 3, 4, 3.0, 6.7);

  return 0;

}

The compiler return the following error:

No matching constructor for initialization of 'point_t<4>'
Candidate constructor not viable: requires 2 arguments, but 6 were provided

What am I'm missing?

like image 461
thewoz Avatar asked Jan 18 '26 05:01

thewoz


1 Answers

What I'm missing?

That a variadic pack can be deduced only if it's in the last position.

So

template<typename ... Args>
point_t(double distance, double value, Args... args)

works and

template<typename ... Args>
point_t(Args ... args, double distance, double value) {

doesn't.

like image 94
max66 Avatar answered Jan 19 '26 20:01

max66



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!