简体   繁体   English

C ++模板的行为和运算符重载

[英]Behavior of C++ templates and operator overloading

I would like to understand the following code behavior 我想了解以下代码行为

#define USE_FRIEND 

class Foo
{
public:
    template <typename T>
    Foo& operator<< (T val)
    {
        std::cout << "Inside Foo" << std::endl;

        return *this;
    }
};

class A
{
public:

#ifdef USE_FRIEND
    friend Foo& operator<<(Foo& f, A& a)
    {
        std::cout << "Inside A" << std::endl;

        return f;
    }
#endif
};

int main()
{
    A a;

    Foo f;

#ifdef USE_FRIEND
    std::cout << " using Friend :: ";
#else
    std::cout << " not using Friend :: ";
#endif

    f << a;

    system("pause");
    return 0;
}

The output for the above code for 2 executions, one with Using friend and another without: 以上代码的输出为2次执行,一次是使用friend而另一次是没有:

case 1: 情况1:

using Friend :: Inside A

case 2: 案例2:

not using Friend :: Inside Foo

I can understand case 2, but can anyone explain case 1 我可以理解案例2,但任何人都可以解释案例1

Overload resolution is complicated business, but here are the two rules that are relevant: 重载解决方案是复杂的业务,但这里有两个相关的规则:

  • The overloads that are viable are: 可行的重载是:

    1. template <typename T> Foo & Foo::operator<<(T)

    2. Foo & operator<<(Foo &, A &)

  • When you call operator<<(f, a) , then both overloads match, and they both match on the nose, deducing T = A in the template. 当你调用operator<<(f, a) ,两个重载都匹配,并且它们都在鼻子上匹配,在模板中推导出T = A There is no difference in exactness, since a reference counts as a "perfect match". 准确性没有区别 ,因为引用计为“完美匹配”。

  • Thus the two overloads are tied, and the resolution would appear to be ambiguous. 因此,两个重载是相关的,并且分辨率看起来是模糊的。 However, there is a tie breaker: No 1 is a template and No 2 is not. 但是,有一个平局:第一个是模板而第二个不是。 In this case, the non-template is a better match. 在这种情况下,非模板是更好的匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM