使用variadric模板时,如何获取第n个参数类型?

Tom*_*ica 1 c++ templates variadic-templates c++17

我想要一个包含n价值观的类,就像std::tuple. 不过,我不能完全使用元组,因为获取值有额外的逻辑 - 它们是按需的。

请以我写的这个类为例:

// somewhere else
template<typename TVal>
TVal valueGetter() { ... };

template<typename ...TColValue>
class ResultRow
{
public:
  template<unsigned int TIndex>
  get_nth_from_variadric<TIndex, TColValue> GetValue() const
  {
    return valueGetter<get_nth_from_variadric<TIndex, TColValue> >();
  }
  

};
Run Code Online (Sandbox Code Playgroud)

我希望它的工作方式是用户只需调用int myVal = GetValue<1>给定的类模板参数即可ResultRow<bool, int>。为此,我需要能够将模板参数的索引转换为类型。

我怎样才能做到这一点?

Ton*_*vel 5

一种方法是将可变参数转发到元组中,然后使用std::get,例如:

#include <iostream>
#include <tuple>

template<size_t N, typename... Args>
auto f(Args&&... args)
{
  return std::get<N>(std::tuple{std::forward<Args>(args)...});
}

int main(void)
{
  std::cout << f<0>("Hello", "world") << ' ' << f<1>("Hello", "world") << f<0>('!') << '\n';
}
Run Code Online (Sandbox Code Playgroud)