Skip to content

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

Closed
@filipsajdak

Description

@filipsajdak

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions