相等数量的模板和函数参数

Fel*_*lix 7 c++ templates variadic-templates c++14

有没有办法生成模板化函数,其中有相同数量的模板参数和函数参数(相同类型)?

如下:

// template function:
template<typename ... Args>
void foo(const std::string& a, const std::string& b, ...) { /*...*/}

// example 1
foo<int>("one argument only");

// example 2
foo<int, double>("first argument", "second argument");
Run Code Online (Sandbox Code Playgroud)

如果存在始终存在的默认函数参数(未模板化)(或多个),该怎么办?

template<typename ... Args>
void foo(int i /* as default */, const std::string& a,
                                 const std::string& b, ...)
 { /*...*/}
Run Code Online (Sandbox Code Playgroud)

甚至可能有,假设函数参数的重复数量(由模板参数的大小计算)?

max*_*x66 10

有没有办法生成模板化函数,其中有相同数量的模板参数和函数参数(相同类型)?

是的:它是(编辑:根据贾斯汀的建议简化;谢谢!)

#include <string>

template <typename, typename T>
using skip_first = T;

template <typename ... Args>
void foo (skip_first<Args, std::string> ... as)
 { }

int main()
 {
   foo<int>("one argument only");

   foo<int, double>("first argument", "second argument");
 }
Run Code Online (Sandbox Code Playgroud)

如果有默认函数参数(或多个)怎么办?

template<typename ... Args>
void foo(int i /* as default */, const std::string& a,
                                 const std::string& b, ...)
 { /*...*/}
Run Code Online (Sandbox Code Playgroud)

如果你想要一个(或多个)不同类型的前面参数,是的,这是可能的.

template <typename ... Args>
void foo (int i, long j, skip_first<Args, std::string> ... as)
 { }
Run Code Online (Sandbox Code Playgroud)

如果您希望前面的参数具有默认值,则不可以:因为参数的可变参数列表不能具有默认值,并且由于给定具有默认值的参数,所有的参数都必须具有默认参数.

甚至可能有,假设函数参数的重复数量(由模板参数的大小计算)?

我想你可以繁殖(重复解压缩更多次)解包部分

template <typename ... Args>
void foo (skip_first<Args, std::string> ... as1,
          skip_first<Args, std::string> ... as2)
 { }
Run Code Online (Sandbox Code Playgroud)

显然,只有当您想要将整数的模板参数的数量相乘时,此解决方案才有效.

  • 你知道,可以使用[`std :: conditional`](https://en.cppreference.com/w/cpp/types/conditional)代替你的自定义`skip_first`. (2认同)