usdot-fhwa-stol / carma-streets

CARMA Streets is a component of CARMA ecosystem, which enables such a coordination among different transportation users. This component provides an interface for CDA participants to interact with the road infrastructure. Doxygen Source Code Documentation: https://usdot-fhwa-stol.github.io/documentation/carma-streets/
10 stars 10 forks source link

Use customization point to allow for "compile time" inheritance for from_json and to_json methods for message serialization and deserialization logic #356

Open paulbourelly999 opened 1 year ago

paulbourelly999 commented 1 year ago

Summary

Provided example by @adamlm :

#include <iostream>
#include <charconv>
#include <string_view>

namespace streets_utils::messages {

namespace customization {

template <typename T>
struct do_from_json {};

}  // namespace customization

template <typename T>
inline constexpr auto from_json = [](std::string_view json_string) {
    return customization::do_from_json<T>::_(json_string);
};

}  // namespace streets_utils::messages

struct S {
    int i{-1};
};

struct T {};

template <>
struct streets_utils::messages::customization::do_from_json<S> {
    static auto _(std::string_view json_string) -> S {
        S s{};

        const auto [ptr, ec] = std::from_chars(std::cbegin(json_string), std::cend(json_string), s.i);

        if (ec != std::errc()) {
            throw std::runtime_error("Could not partse");
        }

        return s;
    }
};

auto main() -> int {
    const auto s = streets_utils::messages::from_json<S>("100");

    std::cout << s.i << '\n';

    return 0;
}

Reasoning for new functionality

Cleaner code