Why does the following code always prints "type is double"? (I have seen this code in StackOverflow)
#include <iostream>
void show_type(...) {
std::cout << "type is not double\n";
}
void show_type(double value) {
std::cout << "type is double\n";
}
int main() {
int x = 10;
double y = 10.3;
show_type(x);
show_type(10);
show_type(10.3);
show_type(y);
return 0;
}
http://en.cppreference.com/w/cpp/language/overload_resolution says:
A standard conversion sequence is always better than a user-defined conversion sequence or an ellipsis conversion sequence.
void show_type(double value) {
std::cout << "type is double\n";
}
if u comment above line then output will be
type is not double type is not double type is not double type is not double
it means that compile always prefer the void show_type(double value)
over void show_type(...)
.
in your case if you want call the method void show_type(...) pass the two or more arguments when u calling this method show_type(firstParameter,secondParameter)
#include <iostream>
void show_type(...) {
std::cout << "type is not double\n";
}
void show_type(double value) {
std::cout << "type is double\n";
}
int main() {
int x = 10;
double y = 10.3;
show_type(x);
show_type(10);
show_type(10.3);
show_type(y);
show_type(4.0,5); //will called this method show-type(...)
return 0;
}
now the output of above line will be
type is double type is double type is double type is double type is not double //notice the output here
more info on var-args
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With