C++朋友在boost::mpl::vector中的每个类

C++ friend each class in a boost::mpl::vector

本文关键字:mpl 朋友 boost C++ vector      更新时间:2023-10-16

如何在boost::mpl::vector中的每个类都有一个类好友?即扩展为的东西

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_ECTOR_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"的朋友。

我认为您需要使用类似Boost.Preprocessor或Pump的东西,来为不同大小的MPL向量专门化您的模板。或者只是手动进行专门化。

你必须通过这种方式专门化你的模板:

template< typename mpl_vector, std::size_t size = boost::mpl::size< mpl_vector >::type::value >
class A;
template< typename mpl_vector >
class A< mpl_vector, 0 >
{
};
template< typename mpl_vector >
class A< mpl_vector, 1 >
{
    friend class boost::mpl::at< mpl_vector, boost::mpl::int_< 0 > >::type;
};