user12956443
user12956443

Reputation:

No matching constructor for initialization of variadic template in C++

Trying to learn Variadic templates and have no clue why this won't compile, the error is: no matching constructor for initialization of 'test<>'.

While we are at it, I like to ask a second question by clarifying my comments within the code.

template <typename ...Args>     // this is just how Variadic template are defined
class test {
 public:
 int arr[sizeof...(Args)];       // this is packing or unpacking? why are 
                                 // dots outside of bracket?

 test(Args... arg)               // this is called packing?
               : arr{arg...}{}   // this is called un-packing?
};

int main(){
 test<> t(1,2,3);
 return 0;
}

Edit: seems like i need to do test <int, int, int>, but why do I have to as this other example works as is:

template <typename ...Args> 
int func(Args... arg)
{
   int a[] = {arg...};
   return sizeof...(arg);
}

int main(void)
{
    std::cout << func(1,2,3,4,5,6) << std::endl;
    return 0;
}

func doesn't need the <int, int ,int.. part.

Upvotes: 1

Views: 164

Answers (1)

NutCracker
NutCracker

Reputation: 12253

Your first example does not work because you need to specify types like:

int main() {
    test<int, int, int> t(1,2,3);
    return 0;
}

If you are able to use C++17, you can take advantage of class template argument deduction and have something like:

int main() {
   test t(1,2,3);
   return 0;
}

But prior to C++17, class template argument deduction did not exist. However, function template argument deduction existed. That's why your second example works without explicitly specifying template types.

Upvotes: 3

Related Questions