c++ - `mpl::plus< mpl::int_<1>, mpl::int_<2>>::type` 与 `mpl::int_<3>` 不是同一类型?

标签 c++ boost c++11 template-meta-programming boost-mpl

下面的代码再现了一个我真的不理解 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>::typethree 的类型不同?

我在尝试解决第 3 章末尾的练习时遇到了这个问题 C++ Template Meta-Programming .我已经试过偷看 <boost/mpl/plus.hpp>以及其中的内容,但是代码太复杂了,我看不懂。

最佳答案

plus 的返回类型只保证是一个整数常量。您无法保证它的确切类型,因此您的断言被允许 失败。

确切的类型是这样的:

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

这是不直观的。一个问题是 plus<int_, int_>理论上可以返回一个 integral_c其中第一个参数的容量比 int_ 大在溢出的情况下。

用于调试 type printer可能有用:

template<typename> print; // undefined instantiation leads to error with name
print<three> x; // nice error message

关于c++ - `mpl::plus< mpl::int_<1>, mpl::int_<2>>::type` 与 `mpl::int_<3>` 不是同一类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11561418/

相关文章:

c++ - 如何通过 autoconf/automake 对 boost 库/ header 包含问题进行故障排除?

c++ - 我可以使用 C++11 智能指针作为 C++ Actor Framework 中的消息返回类型吗?

c++ - Boost 在 CentOS 上找不到 UUID 的 header

C++ 时间(而不是日期)期间

c++ - 链接到 boost 库

c++ - 最佳做法是在方法中传递参数

c++ - 在 C++ 中启动和停止线程内的循环

c++ - IP 地址重叠/在 CIDR 范围内

C++ float 乘以分数

c++ - Boost Spirit - 跳过键值对之间不需要的行