Search code examples
c++functionenumsscopecompile-time

Pass enum in a scope to another as function argument


How to pass enum in a scope to another as function argument? As this is failing:

enum class L;

struct TestClass 
{
   void foo(L n)
   {
      int v = static_cast<int>(n);
      int r[v] = { 9 };
      cout << "\n" << v << "\n";
   }
};


int main() 
{
   enum class L : int 
   {
      A, B, C, D
   };

   TestClass main;
   main.foo(L::D);

   return 0;
}
error: cannot convert ‘main()::L’ to ‘L’
80 | main.foo(L::D);
| ~~~^
|              |
|              main()::L

How to solve this (in exact place, not move enum to a scope else) ?


Solution

  • How to solve this (in the exact place, not move enum to a scope else)?

    Cast the enum while passing as a parameter.

    main.foo(static_cast<int>(L::D));
    

    Then your member function would be

    void foo(int n)
    {
       std::vector<int> r(n, 9);  // used `std::vector` instead of VLA
       std::cout << "\n" << n << "\n";
    }
    

    (See sample code)


    Note that the VLAs are not part of standard C++. Read more in the following post: Why aren't variable-length arrays part of the C++ standard?

    Prefer using std::vector as shown in the above code sample.