Tobi
Tobi

Reputation: 161

c++ overloading function including bool and integer arguments

a simple and I guess easy to answer question (if I did not already got it myself). The following overloaded functions:

void BR(const bool set) { backwardReaction_[nReac_] = set; }
bool BR(const int reactionNumber) const { return backwardReaction_[reactionNumber]; }

The first function is a setter and the second a getter function. backwardReaction_ is of type std::vector<bool>. The problem occurs whenever I want to call the second function. Here I get a compiler error overload function BR(xy) ambigious.

int main()
.
.
const int i = 3;
bool a = chem.BR(i);

The compiler error is equal to:

chemistryTestProg.cpp: In function ‘int main()’:
chemistryTestProg.cpp:74:34: error: call of overloaded ‘BR(const int&)’ is ambiguous
     const bool a = chem.BR(i);
                             ^
In file included from ../../src/gcc/lnInclude/chemistryCalc.hpp:38:0,
                 from ../../src/gcc/lnInclude/chemistry.hpp:38,
                 from chemistryTestProg.cpp:35:
../../src/gcc/lnInclude/chemistryData.hpp:266:18: note: candidate: void AFC::ChemistryData::BR(bool)
             void BR(const bool);
                  ^~
../../src/gcc/lnInclude/chemistryData.hpp:322:22: note: candidate: bool AFC::ChemistryData::BR(int) const
                 bool BR(const int) const;
                      ^~

I guess that I get the problem because of the types bool and int which are identically (true => int(1), false => int(0). As I am changing the getter name to, e.g., bool getBR(const int reactionNumber) {...} everything works fine. So I guess the problem is about the similarities of the bool and int treatment within c++. I also tried a variety of different calls such as:

const bool a = chem.BR(4)
const bool a = chem.BR(int(5))
const bool a = chem.BR(static_cast<const int>(2))
bool a = chem.BR(...)

Thus, I think it is really related to the bool andint overloading arguments. Nevertheless, I made a quick search and did not find too much about these two overload types and resulting problems. Tobi

Upvotes: 1

Views: 1206

Answers (1)

TonyK
TonyK

Reputation: 17114

This is because you declared BR(int), but not BR(bool), to be const. Then when you call BR(int) on a non-const object, the compiler has two conflicting matching rules: parameter matching favours BR(int), but const-ness matching favours BR(bool).

Upvotes: 2

Related Questions