简体   繁体   English

如何在模板类中匹配模板友元函数

[英]How to match template friend function in a template class

I have a template class that declares a friend function which itself has template parameters. 我有一个模板类,它声明了一个友元函数,它本身就有模板参数。 The code looks like this: 代码如下所示:

template <class T>
class C;

template <class T, class U>
void func(C<T>& t);

template <class T>
class C
{
    template <class U>
    friend void func<T, U>(C<T>& t);
private:
    template <class U>
    void f()
    {

    }
};

template <class T, class U>
void func(C<T>& t)
{
    t.f<U>();
}

But when I try to call func , I get a compilation error at the friend line: 但是当我尝试调用func ,我在friend行中遇到了编译错误:

'func': no matching overloaded function found 'func':找不到匹配的重载函数

How can I make func<T, U> friend with C<T> ? 如何用C<T>制作func<T, U>朋友?

The key issue is that the friend you declared, is not the same as the previous declaration you provided. 关键问题是您声明的朋友与您之前提供的声明不同。 The first expects two template parameters, but the second (friend) you defined to accept only one. 第一个需要两个模板参数,但是您定义的第二个(朋友)只接受一个。 Once that is resolved, everything works: 一旦解决了,一切正常:

template <class T>
class C;

template <class U, class T>
void func(C<T>& t);

template <class T>
class C
{
    template <class U, class TT>
    friend void func(C<TT>& t);
private:
    template <class U>
    void f()
    {

    }
};

template <class U, class T>
void func(C<T>& t)
{
    t.template f<U>();
}

int main() {
    C<int> c;
    func<bool>(c);
}

Watch it live . 现场观看

Note I switched U and T up, because I assumed you may want T deduced and U explicitly specified. 注意我切换了UT ,因为我假设你可能想要T推断和U明确指定。

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

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