返回其 INDEX 的第 个参数的模板函数

Template function which returns its INDEX'th parameter

本文关键字:函数 参数 INDEX 的第 返回      更新时间:2023-10-16

如何创建一个模板函数,返回其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%对此解决方案感到满意,但这比问题中的示例要好。