atcoder / ac-library

AtCoder Library
Creative Commons Zero v1.0 Universal
1.89k stars 240 forks source link

Add operator bool to modint #169

Open szdytom opened 1 year ago

szdytom commented 1 year ago

It can be useful if you want something like:

mint x;
// ...
if (x)
  do_sth(x);
mizar commented 1 year ago

https://github.com/atcoder/ac-library/pull/169/commits/95a6273bb67a1440dffe06687d62b13e12937abd Strange to convert zero value to true.

For conversion rules between bool and int types in the C++ language,

https://timsong-cpp.github.io/cppwp/n4659/conv.prom#6

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

https://timsong-cpp.github.io/cppwp/n4659/conv.bool#1

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization, a prvalue of type std​::​nullptr_­t can be converted to a prvalue of type bool; the resulting value is false.

szdytom commented 2 months ago

it is preferred to make conversion function explicit unless any reason not to do so.

This is the place where we need implicit conversion. no one wants to write if ((bool)x) { ... } anyway.

yaito3014 commented 2 months ago

it is preferred to make conversion function explicit unless any reason not to do so.

This is the place where we need implicit conversion. no one wants to write if ((bool)x) { ... } anyway.

You can write if (x) { ... } even if the conversion operator to bool is marked as explicit.

cf. https://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions

TumoiYorozu commented 2 months ago

This repository does not accept requests for new features.

For now, we are not planning to add new features

In this case, I don't think it's necessary because you can add a custom bool cast as shown below:

#include <atcoder/modint>
#include <bits/stdc++.h>

struct mint : public modint998244353 {
    using static_modint::static_modint;
    mint(modint998244353  m) : modint998244353 (m) {}
    operator bool() const { return val() != 0; }
};

int main() {
    mint m(123);

    if (m) {
        puts("not zero");
    } else {
        puts("zero");
    }
}