返回其 INDEX 的第 个参数的模板函数
Template function which returns its INDEX'th parameter
如何创建一个模板函数,返回其index'th参数?
template <int INDEX, typename ...PARAMETERS>
auto &&select(PARAMETERS&& ...parameters);
我知道一个"重量级"解决方案:
template <int INDEX, typename ...PARAMETERS>
auto &&select(PARAMETERS&& ...parameters) {
std::tuple<PARAMETERS&&...> t(parameters...);
return std::get<INDEX>(t);
}
我不太喜欢这种解决方案,因为它在很大程度上取决于编译器优化器。此外,由于不必要的元组,它可能会减慢调试的构建。
或我知道一个不可扩展的(但是性能-OK)的解决方案:
template <int INDEX>
struct SelectNthParameter;
template <>
struct SelectNthParameter<0> {
template <typename PAR0, typename ...TAIL>
static PAR0 &&value(PAR0 &&par0, TAIL&& ...tail) {
return forward<PAR0>(par0);
}
};
template <>
struct SelectNthParameter<1> {
template <typename PAR0, typename PAR1, typename ...TAIL>
static PAR1 &&value(PAR0 &&par0, PAR1 &&par1, TAIL&& ...tail) {
return forward<PAR1>(par1);
}
};
// add more template specializations for 2...inf
是否有更好的(更轻巧,可扩展的)解决方案?
这是我想到的,没有什么地球碎片:
template <int INDEX>
struct SelectNthParameter {
template <typename HEAD, typename ...TAIL>
__attribute__((always_inline))
static auto &&value(HEAD &&head, TAIL &&...tail) {
return SelectNthParameter<INDEX-1>::value(tail...);
}
};
template <>
struct SelectNthParameter<0> {
template <typename HEAD, typename ...TAIL>
__attribute__((always_inline))
static auto &&value(HEAD &&head, TAIL &&...) {
return std::forward<HEAD>(head);
}
};
由于始终为_inline,此解决方案比tuple
更有效(在调试构建中,仅生成2个ASM指令,每个参数比tuple
版本要小得多)。
我可以更确定在发行版中将其优化。我也不100%对此解决方案感到满意,但这比问题中的示例要好。
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数