Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C++ support strongly typed ellipsis?

Can someone please explain to me why C++, at least to my knowledge, doesn't implement a strongly typed ellipsis function, something to the effect of:

void foo(double ...) {  // Do Something } 

Meaning that, in plain speak: 'The user can pass a variable number of terms to the foo function, however, all of the terms must be doubles'

like image 965
Nicholas Hamilton Avatar asked Aug 28 '15 12:08

Nicholas Hamilton


People also ask

What is ellipsis in C?

In the C programming language, an ellipsis is used to represent a variable number of parameters to a function. For example: int printf( const char* format, ... ); The above function in C could then be called with different types and numbers of parameters such as: printf("numbers %i %i %i", 5, 10, 15);

How many parameters the Ellipse function has?

The ellipse function takes four parameters: x, y, width and height.


1 Answers

There is

 void foo(std::initializer_list<double> values);  // foo( {1.5, 3.14, 2.7} ); 

which is very close to that.

You could also use variadic templates but it gets more discursive. As for the actual reason I would say the effort to bring in that new syntax isn't probably worth it: how do you access the single elements? How do you know when to stop? What makes it better than, say, std::initializer_list?

C++ does have something even closer to that: non-type parameter packs.

template < non-type ... values> 

like in

template <int ... Ints> void foo() {      for (int i : {Ints...} )          // do something with i } 

but the type of the non-type template parameter (uhm) has some restrictions: it cannot be double, for example.

like image 91
edmz Avatar answered Sep 28 '22 02:09

edmz