Zhang
Zhang

Reputation: 3346

boost::gregorian::date constructor with Warning C4244

This code snippet works well on my test project. But it compiles with warnings on my working project

auto current_date = boost::gregorian::day_clock::local_day();
const auto nMinYear = current_date.year(); const auto nMonth = current_date.month(); const auto nDay = current_date.day();
const auto nMinYear1 = nMinYear + 1;
boost::gregorian::date holidayDate1(nMinYear1, nMonth, nDay);

at the line of holidayDate1 construction.

Warning C4244 'argument': conversion from 'unsigned int' to 'unsigned short', possible loss of data

My test project is on boost-1.72 and working project on 1.75, both are on Visual Studio 2019.

And I tried using grep_year to wrap nMinYear1 -- holidayDate1(grep_year(nMinYear1 )) -- it doesn't compile.

Edit:

I just tried a forced casting can work around it,

boost::gregorian::date holidayDate1((unsigned short)nMinYear, (unsigned short)nMonth, (unsigned short)nDay);

But I don't understand why the warning happens.

Upvotes: 1

Views: 150

Answers (1)

Bathsheba
Bathsheba

Reputation: 234665

The type of

nMinYear + 1

will be an unsigned int due to implicit widening of the terms in that expression. So nMinYear1 is a const unsigned int, and the compiler emits a warning when that's used in the boost::gregorian::date constructor.

decltype(nMinYear) nMinYear1 = nMinYear + 1;

is a fix.

Upvotes: 1

Related Questions