c++ - 模板和函数参数数量相等

标签 c++ templates c++14 variadic-templates

有没有办法在模板参数和函数参数(相同类型)数量相等的情况下生成模板函数?

喜欢以下内容:

// 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");

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

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

是否有可能拥有重复数量的函数参数(根据模板参数的大小计算)?

最佳答案

Is there a way to generate a templated function where there is an equal number of template params and function params (of the same type)?

是的:它是(编辑:根据 Justin 的建议进行了简化;谢谢!)

#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");
 }

What if there is a default function param (or multiple)?

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

如果您想要一个(或多个)不同类型的前置参数,是的,这是可能的。

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

如果你想要一个有默认值的参数,不:这是不可能的,因为参数的可变列表不能有默认值,因为给定一个有默认值的参数,所有闲置参数都必须有一个默认值参数。

Would it even be possible to have, let's say the duplicate number of function arguments (calculated by the size of the template params)?

我想你可以乘以(重复解压更多次)解压部分

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

显然,只有当您想将模板参数的数量乘以一个整数时,此解决方案才有效。

关于c++ - 模板和函数参数数量相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50778649/

相关文章:

c++ - 小对象堆栈存储、严格别名规则和未定义行为

C++ 在使用 cin 和变量时无法转换输入字符串

c++ - 使用另一个模板类的嵌套名称说明符专门化一个模板类

c++ - 找出汽车的类型

c++ - 可变参数模板类型推导

jquery - Django:单击按钮加载另一个模板

c++ - 类 C 结构中自动字段重新排序的方法

c++ - 为什么struct在C/C++中有两个变量名

c++ - 在自己的初始化器中使用变量

c++ - 构建线程 boost 库