gpt4 book ai didi

C++:从 union 中检索值的模板函数

转载 作者:行者123 更新时间:2023-11-30 01:48:34 26 4
gpt4 key购买 nike

我正在编写一个模板,以从可容纳不同数据类型的集合中获取值(value)。例如变体结构。但是当编译器为其他类型的赋值生成代码时,我会收到警告。例如

struct Variant
{
enum Type
{
_bool,
_int
};
Type type;

union VAL
{
bool bVal;
int nVal;
}val;
};

template <typename ValType>
void GetValue(Variant v, ValType val)
{
if(v.type == Variant::_bool)
{
val = v.val.bVal;
}
else if(v.type == Variant::_int)
{
val = v.val.nVal; // C4800
}
}

Variant v;
v.type = Variant::_bool;
v.val.bVal = true;

bool bVal(false);
GetValue(v, bVal);

警告:

warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

有人可以建议如何重写模板以正确获取值(value)吗?

最佳答案

ValType === boolGetValue 模板中,val 是 bool 类型。因此 val = v.val.nVal; 行导致警告。

为了给特殊类型提供特殊代码,有模板特化。

你可以像这样特化函数模板

template<class T>
void GetValue(Variant v, T & val);

template<>
void GetValue<int>(Variant v, int & val)
{
if (v.type == Variant::_int)
val = v.val.nVal;
}
template <>
void GetValue<bool>(Variant v, bool & val)
{
if (v.type == Variant::_bool)
val = v.val.bVal;
}

注意:v.type 并不能确定将调用哪一个,而是由参数确定。

关于C++:从 union 中检索值的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30314823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com