簡體   English   中英

物理Boost.Units用戶定義的文字

[英]Physical Boost.Units User Defined Literals

現在我們很快就會有用戶定義的文字(UDL),例如在GCC 4.7中,我急切地等待(物理)單元庫(例如Boost.Units )使用它們來簡化文字的表達,例如1+3i3m ,3 3meter13_meter 是否有人使用支持此行為的UDL編寫了Boost.Units的擴展名?

沒人推出這樣的延期。 只有gcc(可能還有IBM?)有UDL,所以可能會有一段時間。 我希望某種單位成為現在開始的tr2。 如果發生這種情況,我相信單位的UDL會出現。

這有效:

//  ./bin/bin/g++ -std=c++0x -o units4 units4.cpp

#include <boost/units/unit.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si.hpp>

using namespace boost::units;
using namespace boost::units::si;

quantity<length, long double>
operator"" _m(long double x)
{ return x * meters; }

quantity<si::time, long double>
operator"" _s(long double x)
{ return x * seconds; }

int
main()
{
  auto l = 66.6_m;
  auto v = 2.5_m / 6.6_s;
  std::cout << "l = " << l << std::endl;
  std::cout << "v = " << v << std::endl;
}

我認為通過你最喜歡的單位來做這件事並不難。

關於將它們放在庫中:文字運算符是命名空間作用域函數。 后綴的競爭將變得丑陋。 我會(如果我得到提升)有

namespace literals
{
...
}

那么Boost用戶可以做到

using boost::units::literals;

與您通常使用的decls一起使用的所有其他內容。 然后你不會受到std::tr2::units破壞。 同樣,如果你自己滾動。

在我看來,使用Boost.Units的文字並沒有太大的好處,因為現有的功能仍然可以實現更強大的語法。

在簡單的情況下,看起來像文字是要走的路,但很快你會發現它不是很強大。 例如,您仍然需要為組合單位定義文字,例如,如何表達1 m / s(每秒1米)?

目前:

auto v = 1*si::meter/si::second; // yes, it is long

文字?

// fake code
using namespace boost::units::literals;
auto v = 1._m_over_s; // or 1._m/si::second; or 1._m/1_s // even worst

使用現有功能可以實現更好的解決方案。 這就是我所做的:

namespace boost{namespace units{namespace si{ //excuse me!
namespace abbreviations{
    static const length             m   = si::meter;
    static const time               s   = si::second;

    // ...
}
}}} // thank you!

using namespace si::abbreviations;
auto v = 1.*m/s;

以同樣的方式: auto a = 1.*m/pow<2>(s); 或者如果你想要更多地擴展縮寫(例如static const area m2 = pow<2>(si::meter);

除此之外你還想要什么?

也許組合解決方案可能就是這樣

auto v = 1._m/s; // _m is literal, /s is from si::abbreviation combined with operator/

但是會有太多的冗余代碼並且增益很小(在數字之后用_替換* 。)

我的解決方案的一個缺點是它使用常見的單字母名稱來調用命名空間。 但除了添加下划線(縮寫的開頭或結尾)之外,我沒有看到解決辦法,如1.*m_/s_但至少我可以構建真實的單位表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM