C++ 在 boost::mpl::vector 中为每个类加好友

标签 c++ boost

如何在 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/

相关文章:

java - 从独立 native 代码调用 java 代码

C++ 枚举类 : Cast to non existing entry

c++/boost program_options 一个选项禁用其他

c++ - boost ASIO 和线程之间的消息传递

c++ - 如何编译以便文件名/行号可用于错误报告工具?

c++ - 缺少元素的结构集

c++ - 减少数组的最大最小和 2 分区的时间复杂度

c++ - 如何使用 Boost.Filesystem 检查两个路径是否指向同一个文件/目录

c++ - 在没有预处理器的情况下从 hana 元组创建函数签名

c++ - boost asio async_read 中的随机 EOF