朋友课程的部分模板专业化?

发布于 2025-02-04 14:06:49 字数 451 浏览 3 评论 0原文

我有一个简单的X类,以及一组模板化的类y< t,u>。我希望所有的类y都恰好是x的所有类y。希望以下是我想要的,但是Friend语句给出了编译错误。

template<typename T, typename U>
class Y {
};

class X {
    public:
        X(int value) : i(value) {}
        const int& getI()    const { return i; }
    private:
        int    i;
        template<class U> friend class Y<X,U>;
};

我不确定完全允许使用朋友语句的模板化(更不用说朋友语句的部分模板化了)。有办法这样做吗?还是我一对一地列出所有朋友?

谢谢, 马特

I have a simple class X, and set of templatized classes Y<T,U>. I'd like all classes Y where the first templatization parameter happens to be X to be a friend of X itself. The following hopefully conveys what I want, but the friend statement gives a compile error.

template<typename T, typename U>
class Y {
};

class X {
    public:
        X(int value) : i(value) {}
        const int& getI()    const { return i; }
    private:
        int    i;
        template<class U> friend class Y<X,U>;
};

I'm not sure templatization of friend statements is allowed at all (let alone partial templatization of friend statements). Is there a way to do this? Or am I stuck listing out all the friends one-by-one?

Thanks,
Matt

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

征﹌骨岁月お 2025-02-11 14:06:49

朋友声明页面在cppreference.com上指定:

朋友声明不能参考部分专业,但可以参考完整的专业

因此Chtz表示您可以有一个非机构专业朋友。

编辑:

另请参阅stackoverflow上的另一个答案: https://stackoverflow.com/a/1046918/5776353

The friend declaration page on cppreference.com specifies:

Friend declarations cannot refer to partial specializations, but can refer to full specializations

So as chtz said you can have a non-partial specialization friend.

Edit:

See also another answer on stackoverflow: https://stackoverflow.com/a/11046918/5776353

温馨耳语 2025-02-11 14:06:49

对于您问题的非机构部分,语法是:

class X {
    template<class T, class U> friend class Y;
};

我想,在大多数情况下,这应该足够。


使用C ++ 11,您实际上可以成为模板的别名:

template<typename T, typename U>
class Y { };

class X {
    public:
        X(int value) : i(value) {}
        const int& getI()    const { return i; }
    private:
        int    i;
        template<class U> using YX = Y<X,U>;
        template<class U> friend class YX;
};

但是,这似乎不起作用(我不确定上面的朋友声明是否完全有任何影响)。

For the non-partial part of your question, the syntax is:

class X {
    template<class T, class U> friend class Y;
};

I guess, in most cases that should be sufficient.


With C++11 you can actually friend a templated alias:

template<typename T, typename U>
class Y { };

class X {
    public:
        X(int value) : i(value) {}
        const int& getI()    const { return i; }
    private:
        int    i;
        template<class U> using YX = Y<X,U>;
        template<class U> friend class YX;
};

However, that does not seem to work (I'm not sure if the friend declaration above has any effect at all).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文