简体   繁体   中英

in visual studio 2015 community c++, how do I fix warning C4838: conversion from 'unsigned int' to 'int' requires a narrowing conversion

I'm trying to write some straight c++ on win32 API (no mfc). With this more modern c++ compiler I get:

warning C4838: conversion from 'unsigned int' to 'int' requires a narrowing conversion

It happens in this code:

EvMap<DlgCtl> DlgCtl::_evMap [] = {
    {IDC_LIST, NM_CLICK, & DlgCtl::Pik},
    {0}
};

riiiiight in front of the closing brace. The 0 for control id means end of array. This code maps a control id and event id to a local function similar to how MFC does.

I guess a narrowing conversion means you're losing precision in the implicit conversion of an unsigned in to int (as an unsigned can hold > 32767 and an int can't).
I'm not sure what the unsigned int is. There's a 0, but that's a signed int, right? The below code is using the list to dispatch class local functions in a winproc-ish class.

template <class T>
struct EvMap {int ctrl, evnt;  void (T::* func)(LPARAM l);};


template <class T>
bool DoEvMap (T *ths, EvMap<T> *evMap, int ctrl, int evnt, LPARAM l)
{
//DBG("DoEvMap ctrl=`d evnt=`d", ctrl, evnt);
    for (int i = 0;  evMap [i].ctrl;  i++) {
//DBG(" - check ctrl=`d evnt=`d", evMap [i].ctrl, evMap [i].evnt);
       if ((ctrl == evMap [i].ctrl) && (evnt == evMap [i].evnt))
           {(ths->*(evMap [i].func)) (l);   return true;}
    }
    return false;
}

I don't want to turn off the warning cuz that's just bad form. I tried putting a static_cast<int>(0) in there for the 0, but same warning.

How can I get on with life with this pesky compiler?

The unsigned int the compiler is warning about is either IDC_LIST or NM_CLICK , since obviously 0 is not an unsigned int .

So either of those two should be signed, or ctrl or evnt should be unsigned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM