非专业化模板中模板专业化的成员访问权限

Member access of template specialisation in unspecialised template

本文关键字:专业化 访问权 权限 访问 非专业 成员      更新时间:2023-10-16

以下代码编译失败(使用clang(:

template<int N>
class Foo {
    public:
        Foo() : value(N) { }
        void getValue(Foo<1>& foo)
        {
            value = foo.value;
        }
    protected:
        int value;
};
int main(int argc, const char * argv[])
{
    Foo<1> fooOne = Foo<1>();
    Foo<2> fooTwo = Foo<2>();
    fooTwo.getValue(fooOne);
    return 0;
}

错误为main.cpp:21:15: error: 'value' is a protected member of 'Foo<1>'。这一切都很好。

我的问题是有没有办法使用朋友来实现这一点?例如,下面的代码会产生同样的错误,但我希望它能起作用。

template<int N>
class Foo {
    public:
        Foo() : value(N) { }
        friend class Foo<1>;
        void getValue(Foo<1>& foo)
        {
            value = foo.value;
        }
    protected:
        int value;
};

当然,我可能非常可怕,并在访问模板参数的受保护成员或http://www.gotw.ca/gotw/076.htm.但我宁愿不要为了一些我可能只是很密集的事情而诉诸那种程度的技巧。

您的friend方式不对。Foo<N>需要成为Foo<1>的朋友,因为它需要访问Foo<1>的内部;您正在使Foo<1>成为Foo<N>friend。为了简单起见,您可以只friend所有这些:

template <int N>
class Foo {
    // mass inter-Foo friendship
    template <int > friend class Foo;
    // rest as you had before
};