C ++:将未知联合传递给函数作为参数

C++: passing unknown union to function as argument

所以我有这样的东西:

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

而且我想编写一个函数,将 "unknown" FoodType 作为参数。

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

如何实施?

这就是你想要的吗?

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

这里可以指定类型,也可以存储fat

在问题的代码中,有一个 union 只有一个成员。 union 需要多个成员才能使用,成员存储在同一个内存地址,所以一次只能使用其中一个。并且两个联合都声明了一个具有相同名称和功能的变量,在我看来你只需要其中一个。

但是,如果您有更复杂的想法,并且确实需要 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。)

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

#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 fat\n"; }

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 fat\n"; }

int main() {
    Apple apple;
    eatFood(apple);
    Banana banana;
    eatFood(banana);
}