加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用boost预处理实例化模板函数和类

发布时间:2020-12-16 07:21:25 所属栏目:百科 来源:网络整理
导读:使用看似标准的w,x,y,z演示,假设我有以下宏试图转换为“可迭代”预处理器宏 #define INSTANTIATE_FUNC(rtype,func_name,...) template rtype func_name w (__VA_ARGS__); template rtype func_name x (__VA_ARGS__); template rtype func_name y (__VA
使用看似标准的w,x,y,z演示,假设我有以下宏试图转换为“可迭代”预处理器宏

#define INSTANTIATE_FUNC(rtype,func_name,...)  
    template rtype func_name< w > (__VA_ARGS__); 
    template rtype func_name< x > (__VA_ARGS__); 
    template rtype func_name< y > (__VA_ARGS__); 
    template rtype func_name< z > (__VA_ARGS__);

为了完整起见,假设我们试图实例化以下内容

struct w { static constexpr int data = 0; };
struct x { static constexpr int data = 1; };
struct y { static constexpr int data = 2; };
struct z { static constexpr int data = 3; };

template <class Data>
void printData(const std::string &prefix) {
    std::cout << prefix << Data::data << std::endl;
}

INSTANTIATE_FUNC(void,printData,const std::string &prefix)

为方便起见,我做了一个minimal gist with a build system,如果你有兴趣尝试,你不必重新创建一切:)

我无法弄清楚如何处理这个问题.唯一的功能(但没有用)刺

#include <boost/preprocessor/list/for_each.hpp>

#define LIST (w,(x,(y,(z,BOOST_PP_NIL))))
#define MACRO(r,data,elem) template void data < elem > (const std::string &prefix);

#define INSTANTIATE_FUNC(rtype,...) 
    BOOST_PP_LIST_FOR_EACH(MACRO,LIST)

这是有效的,但显然是不够的.

>为什么这不适用于序列?

#include <boost/preprocessor/seq/for_each.hpp>
// this does work,my code included the wrong header
// on what I was testing with (seq/for_each_i.hpp)

#define SEQ (x)(y)(z)(w)
#define INSTANTIATE_FUNC(rtype,...) 
    BOOST_PP_SEQ_FOR_EACH(MACRO,SEQ)

>我应该如何处理构建模板rtype func_name< {w,z}> {ARGS,在,__ VA_ARGS__}?我尝试了很多不同的东西,但问题似乎是无法解决只提取w然后遍历__VA_ARGS__,然后继续.我一直在努力让BOOST_PP_LIST_FOR_EACH_R开始工作.这至少是正确的看法吗?
>作为完整性检查,您无法在宏中定义宏吗?精神上的东西

#define INSTANTIATE_FUNC(rtype,...) 
    #define MACRO_##func_name(r,elem) data < elem > (__VA_ARGS__); 
    BOOST_PP_LIST_FOR_EACH(MACRO_##func_name,LIST)

我最终致力于实现LIST / SEQ的可选扩展(如果这意味着更容易实现这一点,那么这意味着什么).感谢您的任何建议/资源.

解决方法

您的问题似乎是您需要在BOOST_PP_(LIST | SEQ)_FOR_EACH中向MACRO提供多个数据,并且您只能使用一个“插槽”.您似乎缺少的事实是,您可以将这些部分分组,例如,元组,然后使用BOOST_PP_TUPLE_ELEM访问MACRO中的不同元素.像这样的东西可以工作:

//These are not required,just to help with readability
#define MACRO_GET_RETURN_TYPE(TUPLE)  BOOST_PP_TUPLE_ELEM(3,TUPLE)
#define MACRO_GET_FUNC_NAME(TUPLE)  BOOST_PP_TUPLE_ELEM(3,1,TUPLE)
#define MACRO_GET_ARGS_SEQ(TUPLE)  BOOST_PP_TUPLE_ELEM(3,2,TUPLE)


#define MACRO(_,DATA,ELEM) template MACRO_GET_RETURN_TYPE(DATA) MACRO_GET_FUNC_NAME(DATA) < ELEM > (BOOST_PP_SEQ_ENUM(MACRO_GET_ARGS_SEQ(DATA)));

// with boost seq
#define SEQ (x)(y)(z)(w)

#define INSTANTIATE_FUNC(rtype,(rtype,BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)),SEQ)

Live on Wandbox

PS:不,你不能在宏中定义一个宏,你在这里发布的代码确实适用于序列,你的要点中的代码不是由于使用了错误的标题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读