I am trying to understand how decltype
works in C++ and so going through examples. Just when i thought i understood what it means, i tried to create examples to confirm that and i got something that i cannot understand. The example is as follows:
#include <iostream>
template<typename T>
auto func2(T a, T b) -> decltype(b < a ? a:b)
{
//return a;//this gives warning of reference to local variable
//return b;//this gives warning of reference to local variable
return (b < a ? a:b);//this does not give warning of reference to local variable
}
int main()
{
std::cout << "Hello World" << std::endl;
int b = func2(4,3);
return 0;
}
As shown in the above code when i use the statement return a;
or return b;
i get a warning saying reference to local variable which is because we should never pass reference or pointers to local variable to outside their scope. But what i don't understand is that why are we not getting the same warning when i use return (b < a ? a:b);
.
My thinking is that decltype(b < a ? a:b)
should result in int&
. And so when i write return (b < a ? a:b);
a reference to local a
or b
should be returned depending on whether which one is greater and we should get the warning.
Aucun commentaire:
Enregistrer un commentaire