Tim*_*imo 4 c++ templates template-meta-programming variadic-templates c++11
我目前正在玩模板元编程。我正在尝试通过使用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);
}
};
Run Code Online (Sandbox Code Playgroud)
此处的问题是,编译器将递归扩展此操作,由于该input参数,在运行时将导致大量递归调用。如果扩展后的代码如下所示,则应该更有效:
bool operator()(const Input& input) const override
{
return input == comp1 || input == comp2 || input == comp3...
}
Run Code Online (Sandbox Code Playgroud)
这有可能吗?
C ++ 17解决方案- 折叠表达式:
template <typename... Ts>
auto anyCondition(Ts... xs)
{
return (xs || ...);
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我在CppCon 2015上发表了关于此片段的演讲:
CppCon 2015:Vittorio Romeo“ for_each_argument解释并扩展了”