2012-12-19 46 views
0

boost::units library提供了將數量值寫入流的不錯方法,see for example使用帶有boost :: units :: quantity值的printf

我可以使用printf的數量值而不是使用輸出流嗎?我有相當數量的代碼使用printf很好地格式化了輸出,我想保持格式化。路過的數量成說

quantity<mass_density> rho = 1.0 * mass_density; 
printf("rho %6.2e\n", rho); 

拋出警告

警告:格式 '%E' 需要類型的 '雙師型' 的說法,但參數2 具有類型 「的boost ::單位::數量<的boost ::單位::單元<的boost ::單位::列表<的boost ::單位::暗淡<的boost ::單位:: length_base_dimension, 的boost ::單位:: static_rational < -0x00000000000000003l > >, 的boost ::單位::列表<的boost ::單位::暗淡<的boost ::單位:: mass_base_dimension, 的boost ::單位:: static_rational <1升> >, 的boost ::單位:: dimensionless_type > >, boost :: units :: homogeneous_system < boost :: units :: list < boost :: units :: si :: meter_base_unit, boost :: units :: list < boost :: units :: scaled_base_unit < boost :: units :: cgs :: gram_base_unit, boost :: units :: scale < 10l,boost :: units :: static_rational <3l> > >,boost :: units :: list < boost :: units :: si :: second_base_unit, boost :: units :: list < boost :: units :: si :: ampere_base_unit, boost :: units :: list < boost :: units :: si :: kelvin_base_unit, boost :: units :: list < boost :: units :: si :: mole_base_unit, boost :: units :: list < boost :: units :: si :: candela_base_unit , boost :: units :: list < boost :: units :: angle :: radian_base_unit, boost :: units :: list < boost :: units :: angle :: steradian_base_unit, boost :: units :: dimensionless_type > > > > > > > > > > > >「[-Wformat]

我可以只使用rho.value()來代替,但我想輸出單位如果可能的話(即使我有更新的格式字符串) 。

我想答案是在這裏,http://www.boost.org/doc/libs/1_52_0/doc/html/boost_units/Reference.html#header.boost.units.io_hpp

+1

如果你打算使用一些C++特性,比如Boost單元,你可能需要使用其他的特性,比如流。大多數Boost類對流操作符IIRC都有重載。如果你需要printf語法,Boost提供了一個基於流的庫,它接受格式字符串。 – ssube

+0

@peachykeen這是說我應該與流一起工作以與boost保持一致嗎? – ccook

+0

我會推薦使用流或Boost的C++ printf庫,是的。它更具慣用性,並且可以幫助您避免這樣的問題,儘管這不是一個全球性的解決方案(使用C++風格的打印時,可變參數更加困難)。 – ssube

回答

4

格式的說明符列表是由語言固定的。 "%e"輸出一個double,"%d"輸出一個int等。沒有什麼會輸出類型爲quantity<mass_density>的對象或類類型的任何其他對象。

你可以有這樣的:

template <typename Unit, typename T> 
string symbolic_units(const quantity<Unit, T> &) 
{ 
    return symbol_string(Unit()); 
} 

int main() 
{ 
    quantity<mass_density> x; 
    x = 3.72 * kilogram_per_cubic_meter; 

    printf ("%g %s\n", x.value(), symbolic_units(x).c_str()); 
} 

但沒有更多。除非你願意使用流媒體課程。

+0

有趣的 - 謝謝你 – ccook

相關問題