dev_sd
dev_sd

Reputation: 1

How LoadString() works in VC++?

I am working on an MFC application where when I write Something like this:CString sName; sName.LoadString(IDS_NAME_STRING) it works fine but when I try to write while initializing in one line like CString sName = sName.LoadString(IDS_NAME_STRING), I am getting error

Error C2440 'initializing': cannot convert from 'BOOL' to 'ATL::CStringT<char,StrTraitMFC_DLL<char,ATL::ChTraitsCRT<_CharType>>>'

I am not getting what's wrong with the latter statement. Can anyone help me to understand this error?

Upvotes: 0

Views: 797

Answers (1)

IInspectable
IInspectable

Reputation: 51345

CString::LoadString returns a value of type BOOL. That's what the error message is telling you. It turned out to be a bit longer as it includes the full template instantiations. It's ultimately saying

cannot convert from 'BOOL' to 'CString'

The solution is what you already have:

CString sName;
sName.LoadString(IDS_NAME_STRING);

If you'd rather have that as a single statement, you'll have to implement a function for it, e.g.

CString load_string(uint32_t id) {
    CString s;
    s.LoadString(id);
    return s;
}

With that you can write

auto s = load_string(IDS_NAME_STRING);

Note that the function load_string mirrors the behavior of the initial code: If a string resource with any given ID cannot be found, it returns an empty string. If you'd rather have failure communicated to clients you could throw an exception.

Upvotes: 2

Related Questions