如何在 boost::mpl::vector 中的每个类(class)都有一个类(class) friend ?即,扩展为:
template <typename mpl_vector>
class A {
friend class mpl_vector[0];
friend class mpl_vector[1];
...
friend class mpl_vector[n];
};
最佳答案
按照 Andres 的建议,使用 boost 预处理器进行处理。
我试过了,不是很好,编译效率会很低。它也仅限于达到 BOOST_MPL_LIMIT_VECTOR_SIZE。如果他的方法有效,那么它可能会更干净一些。
A类.h:
#if BOOST_PP_IS_ITERATING
friend get_elem<mpl_vector, BOOST_PP_ITERATION()>::type;
#else
#ifndef SOME_INCLUSION_GUARD_H
#define SOME_INCLUSION_GUARD_H
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/size.hpp>
class Dummy {};
template <int Exists> struct get_elem_i {
template <typename V, int N> struct get {
//typedef Dummy type;
typedef typename boost::mpl::at< V, boost::mpl::int_<N> >::type type;
};
};
template <> struct get_elem_i<0> {
template <typename V, int N> struct get {
typedef Dummy type;
};
};
template <typename V, int N> struct get_elem {
typedef typename boost::mpl::size<V>::type size;
typedef get_elem_i<N < size::value> elem;
typedef typename elem::get<V, N>::type type;
//typedef Dummy type;
};
template <typename mpl_vector>
class A {
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, BOOST_MPL_LIMIT_VECTOR_SIZE, "classA.h"))
??=include BOOST_PP_ITERATE()
private:
int test_;
};
#endif // SOME_INCLUSION_GUARD_H
#endif
此文件包含自身,因此请确保与 BOOST_PP_ITERATION_PARAMS_1
位中的文件同名。
此外,这段代码还会导致类“Dummy”成为“A”的友元。
关于C++ 在 boost::mpl::vector 中为每个类加好友,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12163721/