c++ - 如何返回映射到可变参数位置的类型

标签 c++ templates variadic-templates

我很喜欢学习元编程,并开始了解一些功能,但我无法调用 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/

相关文章:

c++ - DDS C++ - 数据分发服务

c++ - C++中通过虚表访问函数

c++ - 合并排序实现给出运行时错误?

c++ - 函数模板未正确生成随机数

c++ - 使用构造函数进行引用初始化

c++ - 如何从派生类访问派生基成员?(在 C++ 中)

c++ - 未使用的模板方法中的错误

c++ - 将元组类型转换为另一个元组类型

c++11 可变参数模板编译失败

c++ - C++ 中的模板可变参数