如何生成 OR like 语句编译时?C++
How is it possible to generate an OR like statement compile time? C++
我定义了一个函数和一个类型枚举,如下所示:
enum ActionType : int {
ACTION_FOO, ACTION_BAR, ACTION_BAZ
};
template<int T>
bool TestAction(std::string input, Result& result);
TestAction
返回成功指示器,并将输出写入 Result 参数。它专门用于所有ActionType
值。我这样称呼它:
std::string input = "test";
Result res;
bool ok = TestAction<ACTION_FOO>(input, res) || TestAction<ACTION_BAR>(input, res) || TestAction<ACTION_BAZ>(input, res);
只要一个调用返回 true 值,就不需要调用其他函数,因此 ||
运算符在这里运行良好。
代码按预期工作,但我想避免手动(或使用宏(编写 OR
语句,而是使用模板生成类似的代码编译时间。有可能吗?
如果我从错误的方向处理问题,我可以接受,但是请给我有关如何返工此代码的提示。
以下是
我的做法:
#include <utility>
template <typename T, T ...I, typename F>
bool static_any_of(F &&func, std::integer_sequence<T, I...>)
{
return (func(std::integral_constant<T, I>{}) || ...);
}
template <auto N, typename F>
bool static_any_of_n(F &&func)
{
return static_any_of(std::forward<F>(func), std::make_integer_sequence<decltype(N),N>{});
}
enum ActionType : int
{
ACTION_FOO, ACTION_BAR, ACTION_BAZ,
ActionType_Count,
};
int main()
{
bool ok = static_any_of_n<+ActionType_Count>([](auto index)
{
return TestAction<ActionType(index.value)>(/*...*/);
});
std::cout << ok;
}
我们可以通过编写可以接受多个操作的 TestAction 的第二个版本来做到这一点!
// This is our base case
template<int T>
bool TestAction(std::string input, Result& result);
// This is the general case
template<int T, int T2, int... Ts>
bool TestAction(std::string input, Result& result) {
return TestAction<T>(input, result) || TestAction<T2, Ts...>(input, result);
}
然后,要使用它,我们只需提供以下操作:
std::string input = "test";
Result res;
bool ok = TestAction<ACTION_FOO, ACTION_BAR, ACTION_BAZ>(input, res);
如果您使用的是 C++17,我们还可以使用折叠表达式消除递归:
template<int... Ts>
bool TestActions(std::string input, Result& result) {
return (TestAction<Ts>(input, result) || ...);
}
其他建议:如果不在TestAction
中的任何位置修改input
,则可以通过将input
声明为const std::string&
来消除复制,以便通过引用传递