gpt4 book ai didi

c++ - 使用 boost::mpl,我怎样才能得到有多少模板类不是 "Empty",并用这个数字调用一些宏?

转载 作者:行者123 更新时间:2023-11-30 03:04:42 24 4
gpt4 key购买 nike

我想根据 boost::mpl::eval_if(或类似函数)的结果调用带有一些参数的宏,它可以给出有多少模板参数不为空。假设我们有如下伪代码:

struct EmptyType {  };
template<class arg1=EmptyType, class arg2=EmptyType, class arg3=EmptyType>
class my_class
{
eval_if<is_not_same<arg1, EmptyType>, FILL_MY_CLASS_DEFINE(1)> else
eval_if<is_not_same<arg2, EmptyType>, FILL_MY_CLASS_DEFINE(2)> else
eval_if<is_not_same<arg3, EmptyType>, FILL_MY_CLASS_DEFINE(3)>;
};

我正在尝试根据有多少参数是 EmptyType 来为我的类(class)填充一些内容。我想知道如何通过 Boost.MPL/Preprocessor 或其他一些 Boost 库在 C++03 中完成这样的事情?

最佳答案

您不需要预处理器或 mpl。您需要部分特化:

编辑 这适用于 C++03,实时查看:https://ideone.com/6MaHJ

#include <iostream>
#include <string>

struct EmptyType { };

template<class arg1=EmptyType, class arg2=EmptyType, class arg3=EmptyType>
class my_class
{
// FILL_MY_CLASS_DEFINE(3)
};
template<class arg1, class arg2>
class my_class<arg1,arg2,EmptyType>
{
// FILL_MY_CLASS_DEFINE(2)
};
template<class arg1>
class my_class<arg1,EmptyType,EmptyType>
{
// FILL_MY_CLASS_DEFINE(1)
};
template<>
class my_class<EmptyType,EmptyType,EmptyType>
{
// FILL_MY_CLASS_DEFINE(0)
};

int main(int argc, const char *argv[])
{
my_class<std::string, double, int> a;
my_class<std::string, int> b;
my_class<void> c;

return 0;
}

关于c++ - 使用 boost::mpl,我怎样才能得到有多少模板类不是 "Empty",并用这个数字调用一些宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com