简体   繁体   English

“struct seq<0, 1, 2>{}”数据类型是什么意思?

[英]What “struct seq<0, 1, 2>{}” data type meaning?

    template<int... Is>
    struct seq { };

    template<int N, int... Is>
    struct gen_seq : gen_seq<N - 1, N - 1, Is...> { };

    template<int... Is>
    struct gen_seq<0, Is...> : seq<Is...> { };

when call gen_seq<3> get the final struct seq<0, 1, 2>{} type, I can not understand the "struct seq<0, 1, 2>{}" data type meaning?当调用 gen_seq<3> 得到最终的 struct seq<0, 1, 2>{} 类型时,我无法理解“struct seq<0, 1, 2>{}”数据类型的含义? it means a struct contains three numbers?这意味着一个结构包含三个数字?

It is the usage of Variadic template , which can take any number of parameters.它是Variadic template的用法,它可以接受任意数量的参数。 You can check call stack using __PRETTY_FUNCTION__ in the constructor of these structs.您可以在这些结构的构造函数中使用__PRETTY_FUNCTION__检查调用堆栈。

#include <iostream>
template<int... Is>
struct seq { 
    seq(){std::cout<<__PRETTY_FUNCTION__<<std::endl;}
};

template<int N, int... Is>
struct gen_seq : gen_seq<N - 1, N - 1, Is...> { 
    gen_seq(){std::cout<<__PRETTY_FUNCTION__<<std::endl;}
};

template<int... Is>
struct gen_seq<0, Is...> : seq<Is...> { 
    gen_seq(){std::cout<<__PRETTY_FUNCTION__<<std::endl;}
};
int main() {  
    gen_seq<3> t;
}

Output: Output:

seq<0, 1, 2>::seq() [Is = <0, 1, 2>]
gen_seq<0, 0, 1, 2>::gen_seq() [N = 0, Is = <0, 1, 2>]
gen_seq<1, 1, 2>::gen_seq() [N = 1, Is = <1, 2>]
gen_seq<2, 2>::gen_seq() [N = 2, Is = <2>]
gen_seq<3>::gen_seq() [N = 3, Is = <>]

It's an object of a type containing three numbers.这是一个包含三个数字的类型的 object。 The object has no data members. object 没有数据成员。

It's used to carry around a template parameter pack (of int s) as a single value, eg它用于携带模板参数包( int s)作为单个值,例如

template <typename UnaryOperation, typename... Ts, int... Is>
std::tuple<Ts...> tuple_for_impl(UnaryOperation op, std::tuple<Ts...> input, seq<Is...> /*unused*/) {
    return { op(std::get<Is>(input))... };
}

template <typename UnaryOperation, typename... Ts>
std::tuple<Ts...> tuple_for(UnaryOperation op, std::tuple<Ts...> input) {
    return tuple_for_impl(op, input, gen_seq<sizeof...(Ts)>{});
}

In C++14, it is included in the standard library, as std::integer_sequence在 C++14 中,它被包含在标准库中,为std::integer_sequence

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM