【问题标题】:Pass enum in a scope to another as function argument将范围内的枚举作为函数参数传递给另一个
【发布时间】:2020-09-25 12:27:52
【问题描述】:

如何将一个范围内的枚举作为函数参数传递给另一个?由于这是失败的:

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

如何解决这个问题(在确切的地方,而不是将枚举移动到其他范围)?

【问题讨论】:

    标签: c++ function enums scope compile-time


    【解决方案1】:

    如何解决这个问题(在确切的位置,而不是将枚举移动到其他范围)?

    在作为参数传递时强制转换枚举。

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

    那么你的成员函数就是

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

    (See sample code)


    请注意,VLA 不是标准 C++ 的一部分。在以下帖子中阅读更多信息: Why aren't variable-length arrays part of the C++ standard?

    如上述代码示例所示,首选使用std::vector

    【讨论】:

    • 不意味着 VLA.. 这就是为什么 enum 打算使用真正的编译时间常数
    • C++ 中的 constexpr 函数应该这样做吗?
    【解决方案2】:

    简而言之,问题在于您有一个要在两个地方使用的枚举。对我来说,最自然的解决方案是将枚举放在自己的头文件中,并在需要的地方使用它。

    // 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;
    }
    

    如何解决这个问题(在确切的地方,而不是将枚举移动到其他范围)?

    我意识到我已经以您不希望的方式回答了这个问题,但我不明白您为什么不想将枚举放在自己的文件中。避免这种情况在某些时候会导致问题。 JeJo 解决方案的结果是您可以将任何旧整数传递给 foo() - 它本质上与枚举分离。如果整数值应该来自枚举 L:1)从函数签名中并不明显,2)它很容易被误用,即有人传入了他们不应该传入的值。

    如果将枚举放在自己的头文件中是不可接受的解决方案,我很想知道原因。

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 2011-12-04
      • 1970-01-01
      • 2015-04-23
      • 2017-08-07
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多