dimanche 15 mars 2015

simplest auto type deduction : not working as expected


I really like the use of the auto 'type' as in auto var = ... ,but MSVC 2015 CTP doesn't like my code.


The issue is I am auto-ing an expressions of type short but sometimes it's promoted to int.


I wanted to use it int the initialization of a loop variable like this



COORD pos = ResultFromFunction();
auto rows = pos.Y;
for ( auto i = (rows - rows); i < rows; ++i )
{
coord c{ 0 ,i };
...
}


Here's the some code dealing with the issue ,with the warnings and error :



#include <windows.h>

using t_crd = COORD;
// using alternative below gives same warnings and errors
// struct MY_COORD { short X; short Y; };
// using t_crd = MY_COORD;

void call_test ( t_crd x ) {}

void do_test ()
{

t_crd crd { 10 ,20 };
auto crd2 = COORD{ crd.X ,crd.Y };
t_crd crd3 { crd.X - crd.Y ,crd.Y - crd.X };

auto x4 = crd.X;
auto y4 = crd.Y;
x4 -= crd.Y;
y4 -= crd.X;
t_crd crd4 { x4 ,y4 };
call_test( t_crd{ x4 ,y4 } );

auto x5 = crd.X - crd.Y;
auto y5 = crd.Y - crd.X;
t_crd crd5 { x5 ,y5 }; // warning C4838: conversion from 'int' to 'SHORT' requires a narrowing conversion
call_test( t_crd{ x5 ,y5 } ); // error C2397: conversion from 'int' to 'SHORT' requires a narrowing conversion

short x6 = crd.X;
short y6 = crd.Y;
t_crd crd6 { x6 - y6 ,y6 - x6 };
call_test( t_crd{ x6 - y6 ,y6 - x6 } );

auto x7 = crd.X;
auto y7 = crd.Y;
t_crd crd7 { x7 - y7 ,y7 - x7 };
call_test( t_crd{ x7 - y7 ,y7 - x7 } );

auto x8 = x7 - y7;
auto y8 = y7 - x7;
t_crd crd8 { x8 ,y8 }; // warning C4838: conversion from 'int' to 'SHORT' requires a narrowing conversion
call_test( t_crd{ x8 ,y8 } ); // error C2397: conversion from 'int' to 'SHORT' requires a narrowing conversion

auto x9 = x6 - y6;
auto y9 = y6 - x6;
t_crd crd9 { x9 ,y9 }; // warning C4838: conversion from 'int' to 'SHORT' requires a narrowing conversion
call_test( t_crd{ x8 ,y8 } ); // error C2397: conversion from 'int' to 'SHORT' requires a narrowing conversion
}


I thought this code was OK but it's not according to MSVC 2015 CTP compiler (but Intellisense doesn't indicate it). Is there some obscure little rule that I missed that makes MSVC right ?


And if so why is the same expression a warning in one case and an error in the other case ?




Aucun commentaire:

Enregistrer un commentaire