我很喜欢学习元编程,并开始了解一些功能,但我无法调用 at Works,它需要一个索引来返回映射到变量位置的类型。
#include <iostream>
#include <type_traits>
#include <utility>
template <typename...>
struct type_list {};
template<typename T ,typename... Ns>
auto pop_front(type_list<T, Ns...> t) {
return type_list<Ns...>{};
}
template<typename T ,typename... Ns>
auto front(type_list<T, Ns...> t)
{
return type_list<T>{};
}
template<typename T ,typename... Ns>
auto at(type_list<T, Ns...> t, size_t i)
{
if (i) return at(pop_front(t), i-1);
return front(t);
}
int main()
{
type_list<int, bool, float> x;
at(x,2);
}
最佳答案
如果我们将索引移动到模板参数中,使其成为编译时常量,那么我们可以利用 std::tuple_element
获取提供的索引处的类型,例如
template<size_t Idx, typename... Ts>
auto at(type_list<Ts...>)
{
return std::tuple_element_t<Idx, std::tuple<Ts...>>{};
}
然后我们可以这样调用它
at<2>(x);
应该注意的是,这种方法要求列表中的所有类型都是默认可构造的。
如果您只想使用at
在类似 decltype(at<2>(x))
的上下文中那么您实际上不需要定义该函数,而是可以使用我所说的“元函数”,例如
template<size_t Idx, typename... Ts>
auto at(type_list<Ts...>t) -> std::tuple_element_t<Idx, std::tuple<Ts...>>;
现在您无法运行此函数,但您可以在任何未评估的上下文中使用它,例如decltype(at<2>(x))
,并且列表中的类型不需要默认可构造。
关于c++ - 如何返回映射到可变参数位置的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75733622/