C++ 将可变参数模板参数扩展为语句

标签 c++ c++11 templates variadic-templates template-meta-programming

我目前正在研究模板元编程。我正在尝试使用 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 || ...);
}

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 上就这个片段发表了演讲:
CppCon 2015: Vittorio Romeo “for_each_argument explained and expanded"

关于C++ 将可变参数模板参数扩展为语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623422/

相关文章:

c++ - 虚函数触发 protected 变量的编译错误

c++ - 我可以删除 union 组件而不检查它是否存储该对象吗?

c++ - 如何将模板化类实例作为模板参数传递给另一个模板?

c++ - Arduino清除缓冲区

c++ - 如何使 AddCallback() 更安全 - 对象中不同事件的函数

c++ - 当std::function or lambda functions are involved时C++ 11不能推断类型

c++ - 声明时的默认值

c++ - 使用 std::ostream 打印可变参数包的最简单方法是什么?

c++ - 使用智能指针作为类成员

c++ - 循环包括由于 C++ 类中的枚举