Quote:
Originally Posted by Garrick
how do you cast from one type to another if you're not explicit what type it originally was?
|
Basically just like one normally would, since casting usually requires just the new destination type to be written out in the code. The compiler obviously knows all the time what the original type is. ("auto" is completely a compile time thing.)
If the cast destination type needs to be determined from an "auto" type variable, that's also possible to do, with "decltype".
So nonsense like this is possible but probably never useful with primitive types :
Code:
auto intnumber = 777;
auto destnumber = 0.5;
auto cast_number = static_cast<decltype(destnumber)>(intnumber);
A much more useful example of "auto" usage, which couldn't even be written without "auto" if one wishes to keep the functions as C++11 lambdas for as long as possible :
Code:
auto make_mapping_functions(float minv, float maxv, float middleval)
{
auto normtovaluefunc = [minv,maxv,middleval](float, float, float normval)
{
if (normval<0.5f)
return jmap(normval, 0.0f, 0.5f, minv, middleval);
else return jmap(normval, 0.5f, 1.0f, middleval, maxv);
};
auto valuetonormfunc = [minv,maxv,middleval](float, float, float val)
{
if (val < middleval)
return jmap(val, minv, middleval, 0.0f, 0.5f);
else return jmap(val, middleval, maxv, 0.5f, 1.0f);
};
return std::make_pair(normtovaluefunc, valuetonormfunc);
}
// usage :
auto mapfuncs = make_mapping_functions(0.1f, 10.0f, 1.0f);
NormalisableRange<float> prrange(0.1f, 10.0f, mapfuncs.first, mapfuncs.second);