我不能使用C 17 . 更优选C 11兼容的溶液 .
使用C 11稍微复杂一点(没有 std::index_sequence ,没有 std::make_index_sequence )但是,如果你想保持元组的可变元使用......那就是...如果你真的想要一些东西
foo (std::tuple ... ts)
如果你接受调用模板结构的静态方法,你可以定义一个递归继承自身的模板结构,并递归地定义一个
func ();
func (K t0);
func (K t0, K t1);
func (K t0, K t1, K t2);
哪里 K 是你的
using K = std::tuple;
以下是完整的C 11编译示例
#include
#include
using K = std::tuple;
template
struct getTypeStruct
{ using type = T; };
template
using getType = typename getTypeStruct::type;
template
struct iList;
template <:size_t std::size_t="0u," typename="iList<">>
struct foo;
template <:size_t top std::size_t n int ... is>
struct foo> : public foo>
{
using foo>::func;
static void func (getType ... ts)
{ std::cout << sizeof...(ts) << std::endl; }
};
template <:size_t top int ... is>
struct foo>
{
// fake func, for recursion ground case
static void func ()
{ }
};
int main()
{
foo<>::func({1,'2',3.0}); // print 1
foo<>::func({1,'2',3.0}, {4,'5',6.0}); // print 2
foo<>::func({1,'2',3.0}, {4,'5',6.0}, {7,'8',9.0}); // print 3
}
如果你可以使用C 14,你可以使用 std::make_index_sequence 和 std::index_sequence ,代码变得更好,恕我直言
#include
#include
#include
using K = std::tuple;
template <:size_t ... is>
constexpr auto getIndexSequence (std::index_sequence is)
-> decltype(is);
template <:size_t n>
using IndSeqFrom = decltype(getIndexSequence(std::make_index_sequence{}));
template
struct getTypeStruct
{ using type = T; };
template
using getType = typename getTypeStruct::type;
template <:size_t n="50," typename="IndSeqFrom<N">>
struct foo;
template <:size_t n std::size_t ... is>
struct foo> : public foo
{
using foo::func;
static void func (getType ... ts)
{ std::cout << sizeof...(ts) << std::endl; }
};
template <>
struct foo<0, std::index_sequence<>>
{
static void func ()
{ std::cout << "0" << std::endl; }
};
int main()
{
foo<>::func({1,'2',3.0}); // print 1
foo<>::func({1,'2',3.0}, {4,'5',6.0}); // print 2
foo<>::func({1,'2',3.0}, {4,'5',6.0}, {7,'8',9.0}); // print 3
}
它's a pity you can' t使用C 17,因为在你可以使用variadic unsing 并避免所有递归继承
#include
#include
#include
using K = std::tuple;
template <:size_t ... is>
constexpr auto getIndexSequence (std::index_sequence is)
-> decltype(is);
template <:size_t n>
using IndSeqFrom = decltype(getIndexSequence(std::make_index_sequence{}));
template
struct getTypeStruct
{ using type = T; };
template
using getType = typename getTypeStruct::type;
template <:size_t n typename="IndSeqFrom<N">>
struct bar;
template <:size_t n std::size_t ... is>
struct bar>
{
static void func (getType ... ts)
{ std::cout << sizeof...(ts) << std::endl; }
};
template <:size_t n="50," typename="IndSeqFrom<N">>
struct foo;
template <:size_t n std::size_t ... is>
struct foo> : public bar...
{ using bar::func...; };
int main()
{
foo<>::func({1,'2',3.0}); // print 1
foo<>::func({1,'2',3.0}, {4,'5',6.0}); // print 2
foo<>::func({1,'2',3.0}, {4,'5',6.0}, {7,'8',9.0}); // print 3
}