Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the first function work but the second one doesn't?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

Because the return type of conditional operator will be a common type deduced from its operands.

For bAsInteger ? "1" : "One", the operands are "1" (const char[2]) and "One" (const char[4]), then the common type is deduced as const char *. So bAsInteger ? "1" : "One" always returns const char*, which is used to construct MyStringView later.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading