0

When a function f uses an enum as argument, what's the simplest way to call f with an int instead?

  • (1) This:

    enum State {low=5, high=10};
    
    void f(State t) {
    }
    
    void g(int t) {
        f(t);
    }
    
    int main() {
      g(5);
    }
    

    triggers the error invalid conversion from 'int' to 'State' [-fpermissive].

  • (2) Is it safe to do a simple cast in this case?

    void g(int t) {
        f((State) t);
    }
    

    or is there a better way?

  • (3) The only "correct" solution I found to have a function g with an int parameter is:

    void g(int t) {
        switch (t) {
            case 5: f(low); break;
            case 10: f(high); break;
        }
    }
    

Which of these solutions are correct?

I've already read converting from int to enum and using enum says invalid conversion from 'int' to 'type', but I'm looking for a simpler solution without complexity like static_cast<periods>(atoi(min_prd.c_str())), and I want to compare the different possible solutions, thus it is not a duplicate. Also, my question is not covered by What is the difference between static_cast<> and C style casting?.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • First watch this [Lightning Talk: So You Thought C++ Was Weird? Meet Enums - Roth Michaels - CppCon 2021](https://www.youtube.com/watch?v=SGfk5l85cko), and then decide if you still want to :) I usually don't cast between values and enums except when interacting with hardware (or serialization) that produces numbers, otherwise I just stick with the typesafety C++ offers me . – Pepijn Kramer Jul 07 '22 at 08:04
  • Removed tag C, because the code can't be compiled in C. – 273K Jul 07 '22 at 08:05
  • This question is not covered by the linked questions (not duplicate): what I'm trying to do is a wrapper function `g` with int parameter for the function `f` with enum parameter. – Basj Jul 07 '22 at 08:18
  • XY problem. Why are you doing the conversion in the first place? Work with the `enum`, or work with `int`, not both at the same time. – n. m. could be an AI Jul 14 '22 at 21:10
  • @n.1.8e9-where's-my-sharem. No, example: you have to use a code made by *someone else* (using `enum`), and you want to export it as a DLL using just ... standard `int` so that it can be called easily from another program. – Basj Jul 14 '22 at 21:12
  • You can use a `enum` in a DLL just fine. There is no need to downgrade it to `int`. – n. m. could be an AI Jul 14 '22 at 21:19
  • @n.1.8e9-where's-my-sharem. yes but then when you call this DLL from another language (say Python) you have to define an enum in this destination lang, etc. sometimes it's better to just deal with `int`. – Basj Jul 14 '22 at 21:26

0 Answers0