FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

[SUGGESTION] How to cast int to std::size_t · Issue #104 · hsutter/cppfront · GitHub

Repository navigation

[SUGGESTION] How to cast int to std::size_t #104

Description

Thanks to #93 I was able to implement the main function that takes arguments.

main: (argc : int, argv : **char) -> int = {
    // ...
}

but then argv is a pointer and the pointer arithmetic checks will kick in (another PR is needed to achieve that - already on the list). From the messages provided by the safety check, I know that we recommend using std::span.

When I try to construct std::span I can use pointer and std::size_t argument to construct the span but argc is an int. How to do narrowing conversion in cpp2 way? using argc as std::size_t is not working as it matches

static std::nullptr_t nonesuch = nullptr;

template< typename C >
auto as(...) -> auto {
    return nonesuch;
}

and fails miserably as a runtime crash :(.

What worked for me right now is

    args : std::span<Arg> = (argv, static_cast<std::size_t>(argc));
    // Arg is `using Arg = char*;` as there is an issue with std::span<char*> 
    // or std::span<*char> (star disappears) 

but I believe we can do better.

By the way, returning nonesuch without a warning when something doesn't match defined cases is a really bad idea - I was looking for an error why the below code ends with a crash:

    args : std::span<Arg> = (argv, argc as std::size_t);
    c : std::ifstream = args.back(); // <= here it crashes

Probably it is better to do static_assert for cases that don't match or something that will give a hint of what is not working.

Activity

  1. hsutter commented on Jan 6, 2023

    Owner

    This is now resolved, and the example below works:

    main: (argc: int, argv: **char) -> int = {
        args : std::span<*char> = (argv, argc as std::size_t);
        c : std::ifstream = args.back(); // <= now ok
    }
    

    Thanks!

  2. filipsajdak commented on Jan 6, 2023

    ContributorAuthor

    Excellent solution! Thanks for cooperating on that!

  3. gregmarr commented on Jan 6, 2023

    Contributor

    I thought that there had been a discussion about how to make the main parameters safe by default, but I wasn't able to find it. Is there a plan already spelled out somewhere?

  4. JohelEGP commented on Jan 6, 2023

    Contributor

    There was #63.

  5. gregmarr commented on Jan 6, 2023

    Contributor

    Thanks Johel, I think that's what I was thinking of.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions


      Back | FazBrowse Home | New Git URL