模板的自动返回类型和歧义 [英] Auto return type of template and ambiguity

查看:51
本文介绍了模板的自动返回类型和歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重载的模板函数:

I have an overloaded template function:

template<typename T1, typename T2>
auto overMax(T1 a, T2 b)
{
    std::cout << __FUNCSIG__ << std::endl;

    return b < a ? a : b;
}

template<typename RT, typename T1, typename T2>
RT overMax(T1 a, T2 b)
{
    std::cout << __FUNCSIG__ << std::endl;

    return b < a ? a : b;
}

如果我这样称呼它:

auto a = overMax(4, 7.2); // uses first template
auto b = overMax<double>(4, 7.2); // uses second template

一切正常,但是

auto c = overMax<int>(4, 7.2); // error

导致通话不明确.

为什么使用 int 会如此,然后确定其他哪些类型呢?

Why is it so with int, and OK which other types?

推荐答案

RT 是不可推论的,因此当不提供它时,仅 template< typename T1,typename T2>可以调用自动overMax(T1 a,T2 b).

RT is non deducible, so when not providing it, only template<typename T1, typename T2> auto overMax(T1 a, T2 b) can be called.

(部分地)提供一个模板参数时,这两种方法都是可行的,

When you (partially) provide one template argument, both methods are viable,

但根据论点,一个人可能是更好的候选人:

but depending of argument, one can be a better candidate:

  • 对于 auto b = overMax< double>(4,7.2);//使用第二个模板

overMax< double,int,double> overMax< double,double> 都是可行的.但是 overMax< double,int,double> 是完全匹配的
overMax< double,double> 要求 int 进行 double 转换.

Both overMax<double, int, double> and overMax<double, double> are viable.
But overMax<double, int, double> is exact match
whereas overMax<double, double> requires int to double conversion.

对于 auto c = overMax< int>(4,7.2);//通话不明确

overMax< int,int,double> overMax< int,double> 都是可行的.
但是,这两者都不是更好的匹配方式,也不是更专业的匹配方式,因此通话不明确.

Both overMax<int, int, double> and overMax<int, double> are viable.
But neither is a better match or more specialized, so the call is ambiguous.

这篇关于模板的自动返回类型和歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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