Skip to content

Use NTTP in C++20 as a replacement for macros like CROW_ROUTE #1075

@Rucadi

Description

@Rucadi

With C++20, There is the possibility to use NTTP (Non-type template parameter), while the use of CROW_ROUTE is elegant, I in general dislike macro usage when it can be substituted by a more in-language solution.

It is common to declare something like:

template<std::size_t N>
struct fixed_string {
    char value[N];

    constexpr fixed_string(const char (&str)[N]) {
        std::copy_n(str, N, value);
    }

    constexpr auto operator<=>(const fixed_string&) const = default; 
};

template<std::size_t N>
fixed_string(const char (&)[N]) -> fixed_string<N>;

To allow using constant strings as template-parameters, then we can define our new "route" function, which I call route2:

template<fixed_string Url, typename Handler>
auto route2(Handler&& h) {
    constexpr auto tag = crow::black_magic::get_parameter_tag(Url.value);
    return router_
        .template new_rule_tagged<tag>(Url.value)
        (std::forward<Handler>(h));
}

which makes it possible to define the "hello world" as:

int main()
{
    crow::SimpleApp app;

    app.route2<"/">([]() {
        return "Hello, world!";
    });

    app.port(18080).run();
}

Without macro usage.

Would this be a desirable feature for Crow?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions