gpt4 book ai didi

c++ - 未在可变函数模板中推导出上下文

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:50:44 24 4
gpt4 key购买 nike

据我所知,下面的代码应该是“未推导上下文”(或者不是?)

template <class... X, class Y>
void f(X... args, Y y)
{

}

int main()
{
f(12);
f<int, int, int>(1, 2, 3, 4);
}

但是 g++ 4.9 为 mainf 的两个实例编译它...谁能解释一下?

最佳答案

第一个电话f(12)是病式的。根据 [temp.deduct.type]/p5.7,未出现在参数声明末尾的参数包是非推导上下文:

The non-deduced contexts are:

— [..]

A function parameter pack that does not occur at the end of the parameter-declaration-list

进一步在 [temp.deduct.call]/p1 中:

For a function parameter pack that occurs at the end of the parameter-declaration-list, the type A of each remaining argument of the call is compared with the type P of the declarator-id of the function parameter pack. Each comparison deduces template arguments for subsequent positions in the template parameter packs expanded by the function parameter pack. When a function parameter pack appears in a non-deduced context (14.8.2.5), the type of that parameter pack is never deduced.

[ Example:

template<class ... Types> void f(Types& ...);
template<class T1, class ... Types> void g(T1, Types ...);
template<class T1, class ... Types> void g1(Types ..., T1);

void h(int x, float& y) {
const int z = x;
f(x, y, z); // Types is deduced to int, float, const int
g(x, y, z); // T1 is deduced to int; Types is deduced to float, int
g1(x, y, z); // error: Types is not deduced
g1<int, int, int>(x, y, z); // OK, no deduction occurs
}

— end example ]

因此参数包X...不能通过函数的参数推导,模板参数推导失败。 GCC 接受第一个调用而不是拒绝不推导的模板 12所以这似乎是一个错误。

第二次调用,f<int, int, int>(1, 2, 3, 4)然而,根据 [temp.deduct]/p6,它是合式的。显式指定的模板参数会立即替换函数模板的模板参数。这意味着 X = {int, int, int} .模板参数推导然后继续 Y从最右边的参数推导出为 int :

At certain points in the template argument deduction process it is necessary to take a function type that makes use of template parameters and replace those template parameters with the corresponding templatearguments. This is done at the beginning of template argument deduction when any explicitly specified templatearguments are substituted into the function type, and again at the end of template argument deductionwhen any template arguments that were deduced or obtained from default arguments are substituted.

还请注意 ([temp.deduct]/p2):

There must not be more arguments than there are parameters unless at least one parameter is a template parameter pack, and there shall be an argument for each non-pack parameter.

Clang 不接受最后一个函数调用,但 GCC 接受。我认为这是一个 Clang 错误。


注意有一个开放的CWG issue 1609关于参数包出现后默认参数的使用。还有 LLVM Bug 21774这对 Clang 在这种情况下的行为提出异议。

关于c++ - 未在可变函数模板中推导出上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30344062/

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