Say I have a function:
void foo(const std::string& str);
I could call that function:
foo("my string");
How does std::string
accept a string in place of the type? Is it an overloaded operator? I'm making my own string class, and this feature is essential.
Given a call
foo("my string");
the compiler has to go through various steps to decide which function call that should resolve to.
foo
in the given scope. foo
, it will try to find all the viable functions that can be called with the given argument. If there are more than one matches, it will try to find the best match given the arguments. If there is only one viable, function, then the compiler proceeds. If there are no viable functions, there will be a compile error. foo
, it will try to see if the argument used to call the function matches the argument type. If yes, then the compiler proceeds. If not, there will be a compiler error. The logic for figuring out whether an argument matches the arguments types of a function is too long to describe here. You can read more about it at http://en.cppreference.com/w/cpp/language/overload_resolution and http://en.cppreference.com/w/cpp/language/implicit_conversion .
In your case, "my string"
can be converted to a std::string
by using a constructor of std::string
. The call
foo("my string");
is equivalent to:
foo(std::string("my string"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.