What I am trying to do is, allow a pointer, reference or constant reference to be passed with the setter function:
class A{
std::string * p;
std::string st;
public:
A():p(0)
{}
A& setS(const std::string& s){
std::cout<<"called with const std::string&\n";
st = s;
p = &st;
return *this;
}
A& setS(std::string& s) {
std::cout<<"called with std::string&\n";
p = &s;
return *this;
}
A& setS(std::string* s) {
std::cout<<"called with std::string*\n";
p = s;
return *this;
}
};
int main(){
std::string s;
A a;
a.setS(std::move(s)) //const std::string&
.setS("") //const std::string&
.setS(s) //std::string&
.setS(0); //std::string*
//if std::string* version is not defined,
//setS(0) calls the const std::string& version and throws exception
return 0;
}
But I have seen that, if the pointer version is not there, the setS(0)
calls the const std::string&
version of the setS()
function.
Is there any ambiguity between the pointer and the reference versions or among any others that matter? Is it well defined and expected to work the same way in all compilers?