C++:传递未知并集作为参数
C++: passing unknown union to function as argument
所以我有这样的东西:
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
值。
在问题的代码中,有一个具有单个成员的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。
相关文章:
- 如何创建参数数量未知的函数?
- 参数数据类型未知的可变参数函数
- 当数组大小在C++中未知时,如何在运行时将对字符串数组的引用作为函数参数传递?
- 将参数列表未知的可变参数模板类型定义为 std::map 值类型
- 将未知结构(在运行时)作为模板参数传递
- dynamic_cast到具有未知模板参数的派生类型
- 使用来自C++的任意数量的参数(在编译时未知)调用 Python 函数
- 将向量项传递给具有未知数量参数的函数对象
- C++:传递未知并集作为参数
- 运行 QML 时出现"未知方法参数类型"错误
- 如何将lambda函数传递到具有未知类型和未知参数的构造函数
- nm 未知命令行参数 '-C'?
- 从未知dll(c++)中检索函数(名称、返回类型、参数)
- 当编译时参数未知时,不调用"constexpr"构造函数
- variadic宏可从未知参数集合中生成字符串向量
- 正在尝试使用具有未知类型的模板非类型参数
- 如果数组大小未知,如何将函数数组作为参数传递
- 将未知类作为参数传递
- 带有变量且参数数量未知的c++函数
- 当匹配参数未知时,如何使用RE2库