递归调用可变参数模板函数重载时的歧义调用 [英] Ambiguous call when recursively calling variadic template function overload

查看:89
本文介绍了递归调用可变参数模板函数重载时的歧义调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下这段代码:

template<typename FirstArg>
void foo()
{
}

template<typename FirstArg, typename... RestOfArgs>
void foo()
{
    foo<RestOfArgs...>();
}

int main()
{
    foo<int, int, int>();
    return 0;
}

由于模棱两可的调用 foo < RestOfArgs ...>(); RestOfArgs 只有一个元素时( {int} )。

It does not compile due to ambiguous call foo<RestOfArgs...>(); when RestOfArgs has only one element ({int}).

但这会编译而不会出错:

But this compiles without error:

template<typename FirstArg>
void foo(FirstArg x)
{
}

template<typename FirstArg, typename... RestOfArgs>
void foo(FirstArg x, RestOfArgs... y)
{
    foo(y...);
}

int main()
{
    foo<int, int, int>(5, 6, 7);
    return 0;
}

在第一种情况下为什么会有歧义?

Why is there ambiguity in the first case?

在第二种情况下为什么没有歧义?

Why is there no ambiguity in the second case?

推荐答案

函数模板重载

有有很多规则可以告诉您哪些模板功能更专业(根据给定的参数)。

There is lot of rules to tell which template functions is more specialized (according to given parameters).

关键点

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

对于 foo< int>() ,但不是

template<typename T> void foo(T);
template<typename T, typename... Ts> void foo(T, Ts...);

用于 foo(42)


如果出现平局,如果一个功能模板具有尾随参数包,而另一个则没有,则带有省略的参数被认为比空参数包更专业。

In case of a tie, if one function template has a trailing parameter pack and the other does not, the one with the omitted parameter is considered to be more specialized than the one with the empty parameter pack.

这篇关于递归调用可变参数模板函数重载时的歧义调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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