user13693155
user13693155

Reputation:

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) ?

Upvotes: 2

Views: 579

Answers (2)

castro
castro

Reputation: 429

In a nutshell, the problem is that you have an enum that you want to use in two places. To me, the most natural solution to this is to put the enum in its own header file and use it where it is required.

// my_enum.h
#pragma once

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

// TestClass.h
#pragma once

// Can forward declare L so long as we define the functions in the same cpp
// If original enum is in a namespace it needs to be forward declared in the same namespace
enum class L;

struct TestClass {
    void foo(L n);
};

// TestClass.cpp
#include "TestClass.h"
#include "my_enum.h"

void TestClass::foo(L n)
{
    // do stuff with n
}

// main.cpp
#include "TestClass.h"
#include "my_enum.h"

int main(){

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

    return 0;
}

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

I'm conscious that I've answered the question in a way you did not want, but I do not see why you wouldn't want to put the enum in its own file. Avoiding this will lead to problems at some point. The consequence of JeJo's solution is that you could pass any old integer in to foo() - it is essentially decoupled from the enum. If the integer value is supposed to originate from the enum L: 1) it isn't obvious from the function signature and 2) it is prone to misuse i.e. someone passing in a value they shouldn't.

If putting the enum in its own header file is an unacceptable solution, I'd be interested to know why.

Upvotes: 1

JeJo
JeJo

Reputation: 32722

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.

Upvotes: 1

Related Questions