#What unit conversion libs are there in C++ that support many units?

1 messages · Page 1 of 1 (latest)

solar snowBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

subtle flicker
#

well, as proposed, that doesn't really work because template params are compile time thing, but .at() is a runtime thing

fallen turtle
#

No fucking way

subtle flicker
#

frankly, with something like you've described, meaning user input as strings, there is little other option than a rather extended if statement

#

although you can maybe get around this slightly with a map of maps containing functions as values

#

auto func = convertFuncs["meter"]["foot"]; func(a, b);

#

but you will need to build that map. code wise this will still probably be about as verbose as the if statement

#

maybe, try teh intergoogles

fallen turtle
#

I think there was this one function that was like a switch case but it accepted lambdas and stuff……

subtle flicker
#

how complex are your conversions? I mean something like meters -> feet is a simple scalar multiplication, and vice versa

#

so you could just store scalars in a map as well, concat your units, and use that to look up the key

#

feet = meters * convFactors["meter_foot"];

solar snowBOT
#

Thank you and let us know if you have any more questions!

surreal coral
#

What unit conversion libs are there in C++ that support many units?

wary harbor
#

you could have something like a base unit for example with meter as a base unit for length
1cm -> 0.01m
1m -> 100cm
1ft -> 0.3048m
1m -> 3.28084ft

then to convert cm to ft you can do cm -> m -> ft and every unit would only need to remember how to convert from and to meters

solar snowBOT
#

Thank you and let us know if you have any more questions!

fallen turtle
#

came up with this:

using conversion_types = std::variant<meter*, foot*, centimeter*, mile*, kilometer*>;

std::map<std::string, conversion_types> m = 
{
    { "meter", (meter*)0 },
    { "foot", (foot*)0 },
    { "centimeter", (centimeter*)0 },
    { "mile", (mile*)0 },
    { "kilometer", (kilometer*)0 }
};

conversion_types v = m[unit1];
return std::visit([&value, &unit2, &m](auto arg)
{
    conversion_types v2 = m[unit2];
    return std::visit([&value, arg](auto arg2)
    {
        return units::convert<
            std::remove_pointer_t<decltype(arg)>,
            std::remove_pointer_t<decltype(arg2)>>(value);
    }, v2);
}, v);

making use of std::variant and std::visit

#

std::visit is truly black magic