Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formalize conversion with generic 'from'/'into' free functions #992

Closed
elBoberido opened this issue Dec 15, 2021 · 0 comments · Fixed by #993
Closed

Formalize conversion with generic 'from'/'into' free functions #992

elBoberido opened this issue Dec 15, 2021 · 0 comments · Fixed by #993
Assignees
Labels
enhancement New feature

Comments

@elBoberido
Copy link
Member

elBoberido commented Dec 15, 2021

Brief feature description

While the conversion operator can be implemented for classes, there is no such possibility for enums. To have a consistency in the code base there should be a convention on how to do it. The proposal presents from/into free functions.

Detailed information

Similar to the Rust From/Into trait, there are templated from/into free functions. A developer has to implement only from and into will automatically be available.

This is the implementation in convert.hpp

template <typename F, typename T>
constexpr T from(const F) noexcept
{
    static_assert(always_false_v<F> && always_false_v<T>, "Conversion for the specified types is not implemented!");
}

template <typename T, typename F>
constexpr T into(const F e) noexcept
{
    return from<F, T>(e);
}

The developer can then specialize the from free function for a given enum

enum class Foo
{
    Hypnotoad
};

enum class Bar
{
    Glory
};

template <>
Bar from<Foo, Bar>(Foo e) noexcept
{
    switch(e) {
        case Foo::Hypnotoad:
            return Bar::Glory;
    }
}

On the caller side the developer can just use auto barEnumValue = cxx::into<Bar>(Foo::Hypnotode);

@elBoberido elBoberido self-assigned this Dec 15, 2021
@elBoberido elBoberido added the enhancement New feature label Dec 15, 2021
elBoberido added a commit to ApexAI/iceoryx that referenced this issue Dec 15, 2021
elBoberido added a commit to ApexAI/iceoryx that referenced this issue Dec 15, 2021
elBoberido added a commit to ApexAI/iceoryx that referenced this issue Jan 5, 2022
Signed-off-by: Mathias Kraus <mathias.kraus@apex.ai>
elBoberido added a commit to ApexAI/iceoryx that referenced this issue Jan 5, 2022
Signed-off-by: Mathias Kraus <mathias.kraus@apex.ai>
elBoberido added a commit to ApexAI/iceoryx that referenced this issue Jan 6, 2022
elBoberido added a commit that referenced this issue Jan 10, 2022
…d-into-free-functions-for-conversion

iox-#992 Add templated from/into free functions for conversions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant