A string literal supposed to be deduced as a const char array, then it decays to a const char* pointer. This is why this works:
struct MyStringView
{
template <int N>
MyStringView(const char(&arr)[N]) : str(&arr[0]), size(N - 1){
}
const char* str;
int size;
};
MyStringView getName(int number)
{
switch (number)
{
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
}
}
int main()
{
auto string_view = getName(1);
}
Even though MyStringView doesn’t have a constructor taking a const char*.
But this doesn’t work:
template <bool bAsInteger>
MyStringView getName2(int number)
{
switch (number)
{
// RETURN CANNOT CONVERT FROM CONST CHAR* TO MyStringView
// HOWEVER return bAsInteger ? MyStringView("1") : MyStringView("One") works
case 1: return bAsInteger ? "1" : "One";
case 2: return bAsInteger ? "2" : "Two";
case 3: return bAsInteger ? "3" : "Three";
}
}
int main()
{
string_view = getName2<true>(1);
}
Why doesn’t this work? Why’s it now looking for a const char* constructor?