简体   繁体   English

海湾合作委员会声称一个朋友的功能是超载,暧昧的电话,铿锵编译

[英]GCC claims a friend function to be overloaded, ambiguous call, clang compiles

template <typename T>
class rp {
};

template <template <typename> class P>
struct b {
    template <class, template <typename> class FriendP>
    friend void f(b<FriendP> from);
};

template <class, template <typename> class P>
void f(b<P> from) {
}

int main() {
    b<rp> v;
    f<int>(v);
    return 0;
}

Clang 3.3 (svn) compiles fine, while GCC 4.8 rejects it: Clang 3.3(svn)编译好,而GCC 4.8拒绝它:

main.cpp: In function 'int main()':
main.cpp:17:10: error: call of overloaded 'f(b<rp>&)' is ambiguous
  f<int>(v);
          ^
main.cpp:17:10: note: candidates are:
main.cpp:12:6: note: void f(b<P>) [with <template-parameter-1-1> = int; P = rp]
 void f(b<P> from) {
      ^
main.cpp:8:17: note: void f(b<FriendP>) [with <template-parameter-2-1> = int; FriendP = rp; P = rp]
     friend void f(b<FriendP> from);
                 ^

I wonder why GCC claims f to be overloaded. 我想知道为什么海湾合作委员会声称f超载。 So I guess it's a GCC bug. 所以我猜这是一个GCC错误。

Which compiler is right? 哪个编译器是对的?

Friend injection does no longer exist in the c++ standard, see this for informations about this. c ++标准中不再存在朋友注入,请参阅信息以获取有关此信息的信息。 However, since the friend function declared inside struct b "acts" on a parameter of type "b", the function is found via ADL (argument-dependant lookup). 但是,由于在struct b中声明的friend函数“作用”了类型为“b”的参数,因此通过ADL(依赖于参数的查找)找到该函数。 When this happens 2 different functions having the same signature are declared, and the compiler complains. 当发生这种情况时,会声明具有相同签名的2个不同函数,并且编译器会抱怨。

This is probably what you meant: 这可能是你的意思:

template <template <typename> class P>
struct b {
    template <class, template <typename> class FriendP>
    friend void f(b<FriendP> from){};
};

but don't use this in real code as it is, since "duplicate function" problems can, as you see, easily arise (proper use of namespaces can be of help with this respect). 但是不要在实际代码中使用它,因为正如您所见,“重复函数”问题很容易出现(正确使用命名空间可能对此有所帮助)。

The code can be tested here 代码可以在这里测试

A good reference for the use (as well as a good real-life example of why they are needed) of template friend functions can be found in item 46 of Effective c++ 可以在Effective c ++的第46项中找到模板友好函数的使用(以及为什么需要它们的良好实际示例)的良好参考。

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

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