c++ - 获取可变模板参数的尾部

标签 c++ variadic-templates template-meta-programming

给定这种类型:

template<typename ...As>
struct Base {};

我需要实现一个功能

template<int i, typename ...As>
constexpr auto Tail() {
   static_assert(i < sizeof...(As), "index out of range");
   return ??;
}

它使用来自索引 i 的类型参数列表的尾部返回 B 的实例。

例如,

Tail<0, int, float, double>() -> Base<int, float, double>
Tail<1, int, float, double>() -> Base<float, double>
Tail<2, int, float, double>() -> Base<double>
Tail<3, int, float, double>() -> fails with static assert

我知道如何获取索引 i 处的类型:

template <int64_t i, typename T, typename... Ts>
struct type_at
{
    static_assert(i < sizeof...(Ts) + 1, "index out of range");
    typedef typename type_at<i - 1, Ts...>::type type;
};

template <typename T, typename... Ts> struct type_at<0, T, Ts...> {
    typedef T type;
};

但我无法获得解决整个问题的工作版本。

最佳答案

如果您不介意使用 C++17。甚至不需要 static_assert:

template<unsigned i, typename T, typename ...Ts>
constexpr auto Tail() {
    if constexpr (i == 0)
        return Base<T, Ts...>();
    else 
        return Tail<i - 1, Ts...>();
}


int main(){
    Base<int, double, int> a = Tail<0, int, double, int>();    
    Base<double, int> b = Tail<1, int, double, int>();
    Base<int> c = Tail<2, int, double, int>();
    auto d = Tail<3, int, double, int>();
}

顺便说一句,将 int 更改为 unsigned 以避免负数(几乎)无限递归的可能性。

关于c++ - 获取可变模板参数的尾部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56344737/

相关文章:

C++参数包展开失败

c++ - 为什么我们不能在模板特化的开始/中间使用可变参数模板(以及如何模拟)?

c++ - 可变模板构造函数和移动构造函数

c++ - 使用 make_tuple 方法获取元组和 func 并返回映射元组的最简单方法

c++ - 命名空间内模板类的前向声明

c++ - 可变函数

c++ - (使用 'while' 的插入排序)和(使用 'for' 的插入排序)之间的计算时间有何不同?

swift - Swift 中的元编程

c++ - Visual Studio 编译警告 : Using system operator==/! = 对于 GUID

c++ - 如何为 std::vector 创建一个 shared_ptr?