模板参数包中的6个点是什么? [英] What are the 6 dots in template parameter packs?

查看:147
本文介绍了模板参数包中的6个点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看问题时,我发现自己在 cpp参考网站我注意到一个奇怪和新的语法:

While looking at this question I found myself in the cpp reference site where I noticed a strange and new to me syntax :

template<class Ret, class... Args>
struct is_function<Ret(Args......)volatile &&> : std::true_type {};

是的,6点!最初我认为这是一个错字,但检查libstdc ++ 再次有例如在第444行:

Yep, 6 dots ! Initially I thought this was a typo, but after checking the libstdc++ source again there it was eg at line 444 :

template<typename _Res, typename... _ArgTypes>
struct is_function<_Res(_ArgTypes......) volatile &&> : public true_type { };

这是一个有效的语法吗?点点,用于打包和解包参数包? 6点做什么?

Is this a valid syntax ? Dot dot dot, are used to pack and unpack parameter packs ? What do 6 dots do ?

推荐答案

在这种情况下,这两个是为了不同的目的。第一个用于参数包扩展,第二个用于可变参数列表。这个特定的声明是处理一些函数,这些函数需要一些常规的参数加上一个变量参数列表。

In this case, the two are for different purposes. The first is for parameter pack expansion and the second is for variable argument lists. That particular declaration is to handle functions which take some regular parameters plus a variable argument list.

区别在于运行时和编译时变化。在运行时获取可变数量参数的函数是特殊的。它是一个单一的函数,可以处理来自调用者的可变数量的参数:

The difference is between run-time and compile-time variability. A function which takes a variable number of arguments at run-time is special. It is a single function which can handle a variable number of arguments from the caller:

void f(int x,...) // equivalent to void f(int x ...)
{
    // Do some run-time logic here to determine what to
    // do with parameters after x.
}

这与我们希望能够拥有模板的概念截然不同其使用具有在编译时已知的各种参数的各种函数。例如,我们可以定义一个函数模板,它接受一个函数的指针,并允许参数的数量和类型有所不同:

This is distinct from the notion that we want to be able to have a template which uses a variety of functions with various parameters which are known at compile time. For example, we could define a function template which takes a pointer to a function and allow the number and types of the arguments to vary:

template <typename... Args>
void g(void (*function_ptr)(Args...)) 
{ 
    // We can do logic here to call function_ptr with the proper
    // number of arguments.
}

给定这些函数:

void f1(int);
void f2(int,float);

您可以使用以下任一方式呼叫g:

You can call g with any of them:

g(f1); // fine
g(f2); // also fine

g(f); // error

编译器不知道要使用 Args g 中的参数包。

The compiler wouldn't know what to use for the Args parameter pack in g.

这篇关于模板参数包中的6个点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆