如何在C++Builder 10中将Variant转换为bool?
在旧的bcc32编译器中,我使用以下代码检查某些通用TComponent是否启用:
if ((bool)GetPropValue(c, "Enabled", false))
do_something();
然而,在升级到C++Builder 10并启用新的基于Clang的编译器后,我遇到了以下错误:
[CLANG Error] VclHelpers.cpp(1375): ambiguous conversion for C-style cast from 'System::Variant' to 'bool'
完整的编译器消息表明,Variant的36个转换运算符被认为是合法的候选项:
operator double()
,operator wchar_t*
等。
TControl::Enabled
属性是公共的,所以你可以这样做:if (c->Enabled) ...
。如果你要使用RTTI,那么你可以考虑使用TRttiProperty::GetValue()
代替GetPropValue()
,因为TRttiProperty::GetValue()
返回一个TValue
,它有一个AsBoolean()
方法。TRttiContext ctx; if (ctx.GetType(c->ClassType())->GetProperty("Enabled")->GetValue(c).AsBoolean()) ...
- Remy LebeauGetPropValue()
,那么至少可以摆脱显式类型转换。让编译器为你确定调用哪个转换运算符:bool bEnabled = GetPropValue(c, "Enabled", false); if (bEnabled) ...
。否则,直接调用所需的运算符而不是使用类型转换:if (GetPropValue(c, "Enabled", false).operator bool()) ...
。 - Remy LebeauTComponent*
,并且想要检查TControl::Enabled
属性,只需使用dynamic_cast
进行类型转换为TControl*
(以防TComponent*
指向的不是TControl
的后代),例如:TControl *ctrl = dynamic_cast<TControl*>(c); if ((ctrl) && (ctrl->Enabled)) ...
- Remy Lebeau