考虑下面的代码来自动生成Boost.MPL类型序列(列表或向量)。生成巨大的Boost.MPL类型序列
#include <iostream> // cout
#include <boost/mpl/for_each.hpp> // for_each
#include <boost/mpl/identity.hpp> // identity, make_identity
#include <boost/mpl/int.hpp> // int_
#include <boost/mpl/list.hpp> // list
#include <boost/mpl/next.hpp> // next
#include <boost/mpl/push_front.hpp> // push_front
#include <boost/mpl/vector.hpp> // vector
template<size_t, typename> struct iota_n;
template<typename Value>
struct iota_n<0, Value>
:
boost::mpl::list<> // can change this to boost::mpl::vector<>
{};
template<size_t N, typename Value>
struct iota_n
:
boost::mpl::push_front< typename
iota_n<
N - 1, typename
boost::mpl::next<Value>::type
>::type,
Value
>
{};
// works for N <= 20 and boost::mpl::vector
// works for N <= 247 and boost::mpl::list
typedef iota_n< 247, boost::mpl::int_<0> >::type sequence;
struct print
{
template<typename T>
void operator()(boost::mpl::identity<T>)
{
std::cout << T::value << "\n";
}
};
int main()
{
boost::mpl::for_each<sequence, boost::mpl::make_identity<> >(
print()
);
std::cout << BOOST_MPL_LIMIT_LIST_SIZE << '\n'; // 20 on my system
std::cout << BOOST_MPL_LIMIT_VECTOR_SIZE << '\n'; // 20 on my system
return 0;
}
按照Boost.MPL文档中,boost::mpl::list
序列最多可以有BOOST_MPL_LIMIT_LIST_SIZE
元素,同样的boost::mpl::vector
编译器可以达到BOOST_MPL_LIMIT_VECTOR_SIZE
。这两个宏在我的系统上评估为20。
MSVC++ 2010和Boost 1.47.0确实无法生成超过记录的20个元素的向量。但令人惊讶的是,它可以生成多达247个元素的列表!
有谁知道为什么会发生这种情况?
只是一个猜测,但我认为这是更困难,并涉及更多的元编程来实现一个mpl向量比一个链接列表,它可以只包含一个简单的两个参数模板。对我来说,mpl列表能够处理更多的元素并不令人惊讶,因为这些模板更简单,实例化可能更少,静态递归和分支也更少。 – stinky472 2012-02-29 23:19:06
那么在那种情况下,为什么限制向量和列表序列的宏不同?在我的系统上,都是20,但我可以生成多达247个元素的列表! – TemplateRex 2012-03-01 20:11:23
这些宏可能会根据增强型作者通常可以安全地支持各种编译器的情况而设置实际限制。您可以继续使用列表的事实可能仍然超出了boost作者希望您编写可移植代码的做法。 – stinky472 2012-03-01 23:29:23