我目前正在研究模板元编程。我正在尝试使用 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);
}
};
这里的问题是,编译器会递归地扩展它,这会导致在运行时由于 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 || ...);
}
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;
}
我在 CppCon 2015 上就这个片段发表了演讲:
CppCon 2015: Vittorio Romeo “for_each_argument
explained and expanded"
关于C++ 将可变参数模板参数扩展为语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623422/