通常,当我编写代码时,我经常检查我所做的工作是否有效,但要使用某种断言操作:
std::vector<int> a(1, 1);
std::vector<int> b = {1};
assert(a == b); // this either works, or breaks in a helpful manner
如何在boost mpl
中实现这一点?我目前正试图从两个向量生成一个成对的向量,其中第一个向量表示密钥,第二个向量表示值(即类型):
using Keys = boost::mpl::vector<double, bool, int, char, bool*>;
using Types = boost::mpl::vector<char, char, int, int, int>;
using ExpectedOutput =
boost::mpl::vector<
boost::mpl::pair<double, char>,
boost::mpl::pair<bool, char>,
boost::mpl::pair<int, char>,
boost::mpl::pair<char, int>,
boost::mpl::pair<bool*, int>>;
// now I perform some operation which I _think_ might work
using PairsSequence =
typename boost::mpl::transform<
Keys,
Types,
boost::mpl::pair<boost::mpl::_1, boost::mpl::_2>>;
// Now I attempt to check that it worked
BOOST_MPL_ASSERT(( boost::mpl::equal_to<PairsSequence, ExpectedPairsSequence> ));
但这不起作用,可能是因为boost::mpl::transform
的返回类型是某种模板表达式。如何强制将此输出转换为可以与预期值进行比较的类型?
其他人如何调试他们的MPL代码?Boost似乎没有提供任何工具来检查操作的输出(或者至少我不知道如何使用它们,BOOST_MPL_ASSERT
就是一个很好的例子)。
equal_to
为数值元函数概念建模。您可能希望使用equal
- 您将希望在比较之前应用元函数,我在断言中添加了
::type
- 预期的类型实际上并不匹配,因此除非您匹配它们,否则它将失败
查看Coliru直播
#include <boost/mpl/vector.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/equal.hpp>
using Keys = boost::mpl::vector<double, bool, int, char, bool*>;
using Types = boost::mpl::vector<char, char, int, int, int>;
using ExpectedOutput =
boost::mpl::vector<
boost::mpl::pair<double, char>,
boost::mpl::pair<bool, char>,
boost::mpl::pair<int, int>,
boost::mpl::pair<char, int>,
boost::mpl::pair<bool*, int>>;
// now I perform some operation which I _think_ might work
using PairsSequence =
typename boost::mpl::transform<
Keys,
Types,
boost::mpl::pair<boost::mpl::_1, boost::mpl::_2>>;
BOOST_MPL_ASSERT(( boost::mpl::equal<PairsSequence::type, ExpectedOutput> ));