在解压缩可变参数模板时避免"recursive"函数调用,直到运行时条件

Avoid "recursive" function calls while unpacking variadic templates until runtime condition

本文关键字:函数调用 recursive 条件 运行时 变参 解压缩 参数      更新时间:2023-10-16

基本上,我想在参数包中找到一个满足某些运行时条件的模板。直观地说,我只想遍历参数包的实例化,并找到第一个满足条件的实例。我目前简化的玩具实现来演示我的意思:

首先找到满足其test()XY的结构。

struct X {
bool test(int i) {
flag = i > 10;
return flag;
}
bool flag;
std::string value = "X satisfied first";
};
struct Y {
bool test(int i) {
flag = i > 11;
return flag;
}
bool flag;
std::string value = "Y satiesfied first";
};

此结构找到满足条件的XY的第一个结构。在此示例中,它将整数增加到给定的限制,直到其中一个结构报告其test()成功。

template <typename... Ts> struct FindFirst {
static std::string find_first(int limit) {
return find_first_satisfying(limit, Ts{}...);
}
static std::string find_first_satisfying(int limit, Ts... ts) {
int i = 0;
bool satisfied = false;
while (i < limit && !satisfied) {
satisfied = (ts.test(i) || ...);
i++;
}
return extract(ts...);
}
template <typename T, typename... OtherTs>
static std::string extract(T t, OtherTs... ts) {
if (t.flag) {
return t.value;
} else {
if constexpr (sizeof...(OtherTs) > 0) {
return extract(ts...);
} else {
return "Nobody satiesfied condition";
}
}
}
};

此实现生成的具有不同签名的不同extract()函数与包中的模板一样多。它们被"递归"调用,并导致深度调用堆栈(取决于满足结构的位置)和大字节码。

是否有一种方法可以构造一个循环(在编译时),该循环测试参数包的每个实例化并适当地停止? 另外,关于如何简化整个结构的任何其他建议?

我会给你的代码写这样的东西:

template <typename ... Ts>
std::string find_first_satisfying(int limit, Ts... ts)
{
for (int i = 0; i != limit; ++i) {
std::string res;
bool found = false;
([&](){ if (ts.test(i)) { found = true; res = ts.value; } return found;}() || ...);
if (found) { return res; }
}
return "Nobody satisfied condition";
}

演示

No.在 C++23 中可能不会是这样,但目前无法保证。

但真的有问题吗?我看到的唯一问题是代码很难编写和理解。大字节码意义不大,优化器应该能够内联和优化所有内容 - 只有调试性能应该受到影响(和编译时间)......除非您以使优化器/编译器无法内联它的方式编写程序(通过隐藏函数体)。

附言你不能以某种方式将提取写成运算符并使用...而不是递归吗?不过,由于各种原因,我认为这是一个坏主意。(我看到@Jarod42通过lambda在另一个答案中写的,对我来说看起来不错。