2015-09-04 59 views
2

如何在C++ Builder 10中將變體轉換爲布爾?將變體轉換爲布爾

在舊bcc32編譯器,我用下面的代碼來檢查一些通用TComponent是否啓用:

if ((bool)GetPropValue(c, "Enabled", false)) 
    do_something(); 

然而,升級到C++ Builder中10和啓用新的基於鏘編譯後,我得到以下錯誤:

[CLANG Error] VclHelpers.cpp(1375): ambiguous conversion for C-style cast from 'System::Variant' to 'bool' 

完整的編譯器的消息表明,Variant的轉換操作符36被認爲是合法的候選人:operator double()operator wchar_t*

+0

我一直沒有使用C++ Builder,但一個選項應該是轉換爲int? – user2672165

+0

@ user2672165 - 是的,這似乎工作,雖然它似乎不雅。 –

+0

@JoshKelley:你爲什麼還要爲RTTI煩惱呢? 'TControl :: Enabled'屬性是** public **,所以你可以這樣做:'if(c-> Enabled)...'。如果你打算使用RTTI,那麼你可以考慮使用'TRttiProperty :: GetValue()'而不是'GetPropValue()',因爲'TRttiProperty :: GetValue()'返回一個'TValue',它有一個'AsBoolean )'方法。 'TRttiContext ctx; if(ctx.GetType(c-> ClassType()) - > GetProperty(「Enabled」) - > GetValue(c).AsBoolean())...' –

回答

3

問題是Variant提供了太多的轉換運算符。特別地,下面的操作員使轉換到bool曖昧:

__fastcall operator bool() const; 
__fastcall operator signed char*(); 
__fastcall operator unsigned char*(); 
// etc. - Variant has similar operators for short, int, long, float, double... 
// It calls these "by ref" conversions. 

據我所知,非const重載通常優選爲const過載,但具有> 1替代爲非const轉換到布爾指針轉換以及const布爾轉換,轉換是不明確的。

這可能爲Variant有其轉換以這樣的方式,他們不能毫不含糊地使用設計了一個錯誤,但是從@ user2672165的和@Remy勒博的意見幫助,有幾種解決方法:

// Convert to int instead of bool. 
if ((int)GetPropValue(c, "Enabled", false)) {} 

// Make the Variant const, to avoid the ambiguous non-const conversions. 
if (const_cast<const Variant>(GetPropValue(c, "Enabled", false))) {} 

// Explicitly invoke the desired conversion operator. 
if (GetPropValue(CheckBox1, "Enabled", false).operator bool()) {} 

// Use TRttiProperty instead of Variant. 
RttiContext ctx; 
if (ctx.GetType(c->ClassType())->GetProperty("Enabled")->GetValue(c).AsBoolean()) {}