locked
Why conversion to String^ fails? RRS feed

  • Question

  • In the following code two calls to conversion to String^ fails:

    ref class s sealed { void fun(String ^) { } void foo() { fun("this"); //OK fun(ref new String("this")); //fails, cannot convert parameter 1 from 'const char [5]' to 'const wchar_t *' fun(L"this"); //OK

    auto str = L"this"; fun(str); //fails, cannot convert parameter 1 from 'const wchar_t *' to 'Platform::String ^' } };

    I am not able to understand why it fails.

    1. fun("this") is oK but not fun(ref new String("this"))? How literal "this" is converted to String ^ while calling fun("this")?

    2. In the second case what is the difference between fun(L"this") and fun(str)? In both cases, fun is called with const wchar_t *, then why it fails in the latter case?


    • Edited by John Rick Thursday, October 4, 2012 6:11 AM
    Thursday, October 4, 2012 6:10 AM

Answers

  • See String Construction in Strings (C++/CX)

    The compiler will automatically treat string literals used to construct a String^ as char16 where it can. The examples which work are doing this. The examples which fail are where we aren't constructing directly from the literal and so cannot infer its type (in the first failure) or perform a cast to String^(in the second failure).

    --Rob

    • Proposed as answer by Michael Blome Friday, October 5, 2012 4:51 PM
    • Marked as answer by John Rick Sunday, October 7, 2012 2:41 PM
    Friday, October 5, 2012 2:23 AM
    Moderator