1

I am currently trying to understand the concepts of functions calls and noticed you can write horrible code, but still can make it work by abusing implicit conversion, const and static.

Now I would like to understand why and especially how this works. For example below is a code snippet I used for testing.

The line marked with (1) requires a_const requires it's const modifier and that there is a static function that takes more or less appropriate parameters. Removing any of these two results in a compile error. So how does this work?

#include <iostream>

struct A {

static void func(const int a, int b) {
    std::cout << "A-1"<<std::endl;
}
void func(const int a, float b) {
    std::cout << "A0"<<std::endl;
}
void func(double a, float b) {
    std::cout << "A1"<<std::endl;
}
void func(unsigned int a, char b) {
    std::cout << "A2"<<std::endl;
}
void func(float a, int b) {
    std::cout << "A3"<<std::endl;
}
};

int main() {
const A a_const;
A a;
a_const.func(1.f,1.f); // (1)
// a.func(1.f,1.f);    // (2)
return 0;
}
Imago
  • 521
  • 6
  • 29
  • 1
    You should dig into `16.3.3 Best viable function [over.match.best]` section of the C++ standard. This is really a messy subject. – user7860670 Mar 28 '19 at 10:17
  • @VTT, I am aware this topic is a mess, though did not quite know what to look for. However I found it was finally time for me to immerse myself in it and hopefully becoming more knowledgeable. – Imago Mar 28 '19 at 10:19

1 Answers1

0
a.func(1.f,1.f);

This is an ambiguous call because all of A::func matche and none is a better match than the other.


a_const.func(1.f,1.f);

Is not an ambiguous call since, as a_const is const qualified, all of non-const A::func don't match. The overload set is left with only the static member-function.

YSC
  • 38,212
  • 9
  • 96
  • 149