我如何创建一个模板函数,它返回它的第 INDEX 个参数?
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);
}
我不太喜欢这个解决方案,因为它在很大程度上取决于编译器优化器。此外,由于不必要的元组,它可能会减慢调试构建。
或者我知道一个不太可扩展(但性能还可以)的解决方案:
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);
}
};
因为always_inline,这个解决方案比tuple
更高效(在调试构建中,每个参数只生成2条asm指令,比tuple
版本少很多).
而且我可以更加确定,这将在发布版本中得到优化。我对这个解决方案也不是 100% 满意,但这比问题中的示例要好。
关于c++ - 返回其第 INDEX 个参数的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46396407/