C将可变参数模板参数扩展为语句
发布时间:2020-12-16 10:05:01 所属栏目:百科 来源:网络整理
导读:我正在玩模板元编程.我正在尝试使用tmp创建一个有限状态机.我知道网上有几个实现,但我想自己实现一个练习. 我有一个名为Condition的类,它是两个状态之间转换条件的基类.一个实现是AnyCondition类: templateclass Input,Input comp,Input ... comps class An
我正在玩模板元编程.我正在尝试使用tmp创建一个有限状态机.我知道网上有几个实现,但我想自己实现一个练习.
我有一个名为Condition的类,它是两个状态之间转换条件的基类.一个实现是AnyCondition类: template<class Input,Input comp,Input ... comps > class AnyCondition: public Condition<Input> { public: AnyCondition() {} bool operator()(const Input& input) const override { return input == comp || AnyCondition<Input,comps...>()(input); } }; 这里的事情是,编译器将递归地扩展它,由于输入参数导致在运行时进行大量递归调用.如果扩展代码是一个如下声明,它应该更有效率: bool operator()(const Input& input) const override { return input == comp1 || input == comp2 || input == comp3... } 这有可能吗? 解决方法
C 17解决方案 –
fold expression:
template <typename... Ts> auto anyCondition(Ts... xs) { return (xs || ...); } wandbox example C 11解决方案 – for_each_argument: template <typename TF,typename... Ts> void for_each_argument(TF&& f,Ts&&... xs) { (void)(int[]){(f(std::forward<Ts>(xs)),0)...}; } template <typename... Ts> auto anyCondition(Ts... xs) { bool acc = false; for_each_argument([&acc](bool x){ acc = acc || x; },xs...); return acc; } wandbox example 我在CppCon 2015上谈到了这个片段: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |