Why is an unsuitable overloaded function called?

Why is the "double type" always printed in the following code? (I saw 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;
}
+4
source share
2 answers

http://en.cppreference.com/w/cpp/language/overload_resolution says:

A standard conversion sequence is always better than a custom conversion sequence or an ellipsis conversion sequence.

+9
source
   void show_type(double value) { 
        std::cout << "type is double\n"; 
    }

if u comment is above line then output will be

type is not double
type is not double
type is not double
type is not double

this means that compilation always prefers void show_type(double value)over void show_type(...).

, void show_type (...) 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;
}

type is  double
type is  double
type is  double
type is  double
type is not double  //notice the output here

var-args

0

Source: https://habr.com/ru/post/1614857/


All Articles