Skip to content

Cannot decide between different fmt::styles at runtime, gives crashes. #3625

Description

@TobiSchluter

This crashes at runtime:

#include <fmt/core.h>
#include <fmt/color.h>

int main()
{
    auto quality = [&] {
        return fmt::styled(std::string_view("great"), fmt::emphasis::bold);
    };
    auto quality2 = quality();
    bool condition = false;
    auto quality3 = [&] {
        // Doesn't compile if this is uncommented.
        //if (condition) return fmt::styled("not great", fmt::emphasis::bold);
        return fmt::styled("great", fmt::emphasis::bold);
    }();

    // Either of the following two crashes at runtime
    fmt::print("result: {}\n", quality());
    //fmt::print("result: {}\n", quality2);

    // This works, but can only work for alternatives of the same length.
    fmt::print("result: {}\n", quality3);
}

https://godbolt.org/z/3cq9eWhnM

I'm only using the string_view here because in the real world I use multiple strings of different length which end up having different types when styled and thus can't be returned from a function as for quality3. It would be great if this or something equivalent worked, nice if the limitations were documented, good if there were a compiler error and bad (for me) if I'm just too dumb. A workaround is to format the quality flag before storing it of course, but that means formatting twice.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions