4

以下のコードは、boost MPL ライブラリについて私が本当に理解していない動作を再現しています。

#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/plus.hpp>

using namespace boost;

int main() {
  typedef mpl::int_<1> one;
  typedef mpl::int_<2> two;
  typedef mpl::int_<3> three;
  // The following line breaks compilation...
  // static_assert( is_same< mpl::plus<one,two>::type, three >::type::value, "Not the same type");
  // ...while this works
  static_assert( mpl::plus<one,two>::type::value == three::value , "Not the same value");
  return 0;
}

私が持っている質問は、なぜmpl::plus<one,two>::typeと同じタイプではないのthreeですか?

C++ Template Meta-Programmingの第 3 章の最後にある演習を解こうとしているときに、この問題に遭遇しました 。私はすでにその中のインクルードをのぞき見しようとしまし<boost/mpl/plus.hpp>たが、コードが複雑すぎて理解できませんでした。

4

1 に答える 1

5

の戻り型はplus、積分定数であることが保証されているだけです。正確なタイプを保証するものではないため、アサーション失敗する可能性があります。

正確なタイプは次のとおりです。

mpl::plus<one,two>::type == mpl_::integral_c<int, 3>
three == foo<mpl_::int_<3> >

これは直感的ではありません。1つの問題は、理論的には、オーバーフローの場合よりも最初の引数の容量が大きいplus<int_, int_>aを返すことができるということです。integral_cint_

デバッグには、次のtype printerことが役立ちます。

template<typename> print; // undefined instantiation leads to error with name
print<three> x; // nice error message
于 2012-07-19T13:22:03.397 に答える