I was recently asked this question in an interview of C++ where I was asked to improve the below piece of code which fails when adding two integers results in the result being long and return type needs accordingly to be derived.
Here the below code fails because the decltype based derivation is not intelligent enough to identify based on actual values of input but the type and derives return type as same. Hence we need perhaps some metaprogramming template technique to derive the return type as long if T is int. How can this be generalized any hints or clues ? I feel that decltype wont be helpful here.
#include<iostream>
#include<string>
#include<climits>
using namespace std;
template<typename T> auto adder(const T& i1, const T& i2) -> decltype(i1+i2)
{
return(i1+i2);
}
int main(int argc, char* argv[])
{
cout << adder(INT_MAX-10, INT_MAX-3) << endl; // wrong.
cout << adder<long>(INT_MAX-10, INT_MAX-3) << endl; // correct!!.
return(0);
}
Aucun commentaire:
Enregistrer un commentaire