Consider the following code:
#include <optional>
#include <string_view>
int main() {
std::optional<std::string_view> opt { "abc" };
std::cout << opt.value();
return 0;
}
It compiles and when run outputs "abc" to the console. Why does it compile? The first line of code in main should be:
std::optional<std::string_view> { std::string_view { "abc" } };
How does the compiler know to make a call to the string_view constructor with the literal? This seems like it is doing more than just type deduction which I have seen before. Here it seems like the compiler is adding code to my source, i.e. a call to a constructor.
How does the compiler know to make a call to the string_view constructor with the literal?
std::optional
has a constructor with the form of
template < class U = T >
constexpr optional( U&& value );
This is used to directly initialize the underlying object only if T
can be constructed from U
, which it can in this case using std::string_view
's
constexpr basic_string_view(const CharT* s);
constructor.
This seems like it is doing more than just type deduction which I have seen before
You told the compiler you have a std::optional<std::string_view>
, so it doesn't need to determine what type of optional you have. It does determine what U
would be in the constructor, and sees that is a type which can be used to construct a std::string_view
with, and so it calls the constructor to do just that since it satisfies the requirements.