gpt4 book ai didi

c++ - 模板参数包中的 6 个点是什么?

转载 作者:IT老高 更新时间:2023-10-28 12:39:51 43 4
gpt4 key购买 nike

在查看 this 时我在 cpp reference site 中发现的问题我注意到一个奇怪的新语法:

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

是的,6 个点!最初我认为这是一个错字,但在检查了 libstdc++ source 之后再次出现在第 444 行:

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

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

最佳答案

为什么libstdc++is_function的实现中使用... ...?如果我们查看 std::is_function 的 cppreference 部分它提供了一个示例实现,并针对第一个 ... ... 案例:

// specialization for variadic functions such as std::printf
template<class Ret, class... Args>
struct is_function<Ret(Args......)> : std::true_type {};

所以我们需要第二组 ... 来匹配像 printf 这样的可变参数函数:

           Comma optional as per 8.3.5 [dcl.fct] 
|
v
Ret(Args... ...)
^ ^
| |
Match a function with a variable number of arguments
|
and the function is a variadic function

注意,我们有像 fprintf 这样的函数,在可变参数项之前有两个参数,我们也需要匹配它们。实际上,如果我们使用该实现并尝试在没有 ... ... 特化的情况下匹配 printf 那么它会失败 see it live .

这篇文章涵盖了语言的这个角落C++11's six dots :

I was mucking around the other day and discovered this nice little oddity:

template <typename... Args>
void foo(Args......);

As it turns out, ...... can be totally valid C++11. This is what happens when backward compatibility mixes with new hotness.

// These are all equivalent.

template <typename... Args> void foo1(Args......);
template <typename... Args> void foo2(Args... ...);
template <typename... Args> void foo3(Args..., ...);

Hopefully the last one shows what is happening here. [...]

为什么这是有效的?我们可以看到 , ... 是 C++11 标准草案 8.3.5 中的 ... 的同义词[dcl.fct] 语法如下:

parameter-declaration-clause:
parameter-declaration-listopt...opt
parameter-declaration-list , ...

然后说:

[...] Where syntactically correct and where “...” is not part of an abstract-declarator, “, ...” is synonymous with “...”. [...]

关于c++ - 模板参数包中的 6 个点是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33502509/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com