2011-01-14 48 views
2

我有一些類型T,在某些情況下,它可能是,例如char,但我想輸出其整數值,而不是字符。因爲這是有以下幾點:鑄造int或浮動取決於is_integer

typedef (std::numeric_limits<T>::is_integer ? int : float) FormatType; 
os << static_cast<FormatType>(t); 

然而,這不能編譯,指出「error C2275: 'int' : illegal use of this type as an expression」。前綴intfloattypename不旋轉的問題。我在這裏錯過了什麼?

下,我相信這是等價的,工作原理:

if(std::numeric_limits<T>::is_integer) 
{ 
    os << static_cast<int>(t); 
} 
else 
{ 
    os << static_cast<float>(t); 
} 
+0

這是`C++ 0x`? – Troubadour 2011-01-14 11:09:10

+0

@Troubadour:沒有 – dukedave 2011-01-14 11:10:56

+1

BTW,這將是等效的除了一個事實,即前者是無效的。 :) – 2011-01-14 11:14:56

回答

3

缺少什麼我在這裏?

你試圖使用類型爲表達式。 C++根本不允許這樣做。你可以通過元編程使用所謂的「編譯時if」。例如,我相信升壓提供以下功能:

typedef if_<std::numeric_limits<T>::is_integer, int, double>::type FormatType; 

os << static_cast<FormatType>(t); 

在另一隻手,你的第二個解決方案行之有效,編譯器會找出一個分支永遠是真實的,並消除它。所以在兩種情況下性能都是一樣的(實際上,應該生成完全相同的代碼)。

2

嘗試使用積分的推廣:

os << +t; 

你會得到一個int出它的整體式,或者你如果是原始浮點型,則爲原始浮點型。

0

GCC接受它,不知道別人:

template<bool Expression, typename TrueResult, typename FalseResult> 
    class conditional_type; 

template<typename TrueResult, typename FalseResult> 
class conditional_type<1, TrueResult, FalseResult> { 
public: 
    typedef TrueResult R; 
}; 

template<typename TrueResult, typename FalseResult> 
class conditional_type<0, TrueResult, FalseResult> { 
public: 
    typedef FalseResult R; 
}; 

typedef conditional_type<std::numeric_limits<T>::is_integer,int,float>::R FormatType;