C++:传递未知并集作为参数

C++: passing unknown union to function as argument

本文关键字:参数 未知 C++      更新时间:2023-10-16

所以我有这样的东西:

struct FoodType {
    union {
        int fat = 2;
    } Apple;
    union {
        int fat = 3;
    } Banana;
} FoodType;

我想编写一个函数,将"未知"的 FoodType 作为参数。

void eatFood(FoodType type) { /* do something */ }

如何实现这一点?

您在问题中提供的枚举解决方案的替代方案是实例化:

#include <iostream>
struct FoodType {
    FoodType(int f) : fat(f) {}
    int getFat() { return fat; }
    int fat;
};
void eatFood(const FoodType& type) { std::cout << "I ate " << type.getFat() << " grams of fatn"; }
int main() {
    FoodType apple(2);
    eatFood(apple);
    FoodType banana(3);
    eatFood(banana);
}

或者,对于更复杂的情况,可以使用多态性,但这里似乎矫枉过正:

#include <iostream>
struct FoodType {
    virtual int getFat() const = 0;
};
struct Apple: FoodType {
    int getFat() const { return 2; }
};
struct Banana: FoodType {
    int getFat() const { return 3; }
};
void eatFood(const FoodType& type) { std::cout << "I ate " << type.getFat() << " grams of fatn"; }
int main() {
    Apple apple;
    eatFood(apple);
    Banana banana;
    eatFood(banana);
}

这就是你所追求的吗?

struct Food {
  enum class Type { Apple, Banana };
  int fat = 2;
  Type type = Apple;
};

您可以在此处指定类型,也可以存储fat值。

在问题的代码中,有一个具有单个成员的unionunion需要多个成员才能使用,则成员存储在相同的内存地址中,因此您一次只能使用其中一个成员。两个联合都声明了一个具有相同名称和函数的变量,在我看来,您只需要其中一个。

但是,如果您有更复杂的想法,并且您确实需要 union ,那么您应该尝试这样的事情:

struct Food {
  enum class Type { Apple, Banana };
  Type type = Apple;
  union {
    int banana;
    double apple;
  };
};
Food food;
food.type = Food::Type::Apple;
food.apple = 2;

在这里,您可以使用 banana 元素或 apple 元素,并且您将使用 type 元素来知道要使用哪一个。

但是如果你需要它,

如果你的编译器还不支持它,你最好使用新的std::variant(或 boost::variant(。

从您的评论来看,您想要枚举。C++有枚举:

enum FoodType
{
    Apple,
    Banana
};
void EatFood(const FoodType & foodType)
{
    switch (foodType)
    {
    case Apple:
        /* do something */
        break;
    case Banana:
        /* do something */
        break;
    default:
        /* handle invalid value */
        break;
    }
}

如果需要这些整数值,请执行以下操作:

enum FoodType
{
    Apple=2,
    Banana=3
};

如果要严格键入,请执行以下操作:

enum class FoodType
{
    Apple=2,
    Banana=3
};

(然后在EatFood中,你必须使用FoodType::Apple和FoodType::Banana。