在解压缩可变参数模板时避免"recursive"函数调用,直到运行时条件
Avoid "recursive" function calls while unpacking variadic templates until runtime condition
基本上,我想在参数包中找到一个满足某些运行时条件的模板。直观地说,我只想遍历参数包的实例化,并找到第一个满足条件的实例。我目前简化的玩具实现来演示我的意思:
首先找到满足其test()
的X
和Y
的结构。
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";
};
此结构找到满足条件的X
和Y
的第一个结构。在此示例中,它将整数增加到给定的限制,直到其中一个结构报告其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在另一个答案中写的,对我来说看起来不错。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 在解压缩可变参数模板时避免"recursive"函数调用,直到运行时条件