What is the rationale behind the syntax chosen to declare template friends?

前端 未结 2 519
被撕碎了的回忆
被撕碎了的回忆 2021-02-14 23:37

Declaring template function friends involves some incredibly unintuitive syntax, even for C++! What is the rationale behind the choice of syntax for the extra <>

相关标签:
2条回答
  • 2021-02-15 00:05

    Wait. You are not declare a friend template. You declare a specialization of a template as friend! As such, why would you want to put a template clause there?

    The syntax to name specializations of function templates is by teplateName<ArgumentList>, and that is what you shall use according to the Standard in the friend declarations.

    If you want to befriend the whole template and all specializations generated and explicitly specialized, you can still do that, and then you can use a template clause

    template<typename U>
    friend void bar(Foo<U>);
    
    0 讨论(0)
  • 2021-02-15 00:07

    Quoting this page:

    The non-template function is called because a non-template function takes precedence in overload resolution.

    So my guess the friend void bar<>(Foo<T>); is intuitive because you want to make sure it's the template function you are calling and not an overload for Foo<T>. There would otherwise no way for the compiler to notice if the templated or the non-templated function is the class'es friend.

    Why the <> syntax is used and not the template syntax is not clear to me.

    0 讨论(0)
提交回复
热议问题