0

Suppose I have a (compile-time) fixed set of values from a certain type, e.g. foo1, foo2, foo3, foo4 of type Foo. At runtime, I have a variable my_foo of type Foo, and I want to be able to check whether it is one of my foo's - not by individual independent check. So, I basically want to be able to write something like:

if ( my_foo is_in {foo1, foo2, foo3, foo4} ) do_stuff(); 

can I implement such an is_in operator (could be called something else, e.g. member_of, in, found_in or whatever). Is this possible?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • You mean [like this](https://github.com/klmr/named-operator) (i.e. `my_foo {foo1, foo2, foo3, foo4}`)? – Konrad Rudolph Sep 14 '22 at 09:52
  • C++ does not support custom operators. – Quimby Sep 14 '22 at 09:55
  • @Quimby Well check the link I posted and be amazed. – Konrad Rudolph Sep 14 '22 at 10:03
  • @KonradRudolph I am amazed, still, it is not a custom operator any more than `std::boolalpha` is. But I think it's very cool and like this "abuse", I just wanted to make the point clear for OP. BTW, it likely won't play nicely with clang-format's spacing rule which is unfortunate, or have you tested it? – Quimby Sep 14 '22 at 10:27
  • 1
    @Quimby You can probably create a custom spacing rule for it but I’ve never used linters in C++ so I have no experience with this. Anyway, I’m confident that einpoklum is aware that C++ doesn’t support custom operators, so I think they were after a similar hack. – Konrad Rudolph Sep 14 '22 at 10:32
  • @Quimby: With just tiny bit of macro work, it [can support them just fine](https://stackoverflow.com/a/70328397/1593077)... – einpoklum Sep 14 '22 at 11:00
  • @KonradRudolph: That's very nice, but not quite all the way there syntax-wise. You can get proper syntax like in my question; see [here](https://stackoverflow.com/a/70328397/1593077). On the other hand - I use a macro, and you might not be using one (or are you?) – einpoklum Sep 14 '22 at 11:02
  • @einpoklum I’m not against macro use, but unhygienic, unscoped macros are a pretty big no-no, indeed. And I think you’ll agree that the macro `MYLIBNAME_IS_ONE_OF` is completely unusable, especially compared to ``. – Konrad Rudolph Sep 14 '22 at 13:03

0 Answers0