1

I'm trying to create a template class with a friend function which is inside a nested namespace. It works fine if I remove all the namespaces or if I remove all the templatization. But with both in place it won't compile. Let's look at some code:

namespace MyNamespace
{
    // Forward declaration
    template <typename Type>
    class Container;

    // Forward declaration
    namespace AccessPrivateImplementation
    {
        template <typename Type>
        Type getValue(Container<Type>* container);
    }

    // Templatized class
    template <typename Type>
    class Container
    {
        friend Type AccessPrivateImplementation::getValue(Container<Type>* volume);
    private:
        Type value;
    };

    // Friend function inside a namespace
    namespace AccessPrivateImplementation
    {
        template <typename Type>
        Type getValue(Container<Type>* container)
        {
            return container->value;
        }
    }
}

int main(int argc, char* argv[])
{
    MyNamespace::Container<int> cont;
    MyNamespace::AccessPrivateImplementation::getValue(&cont);
    return 0;
}

The compiler (VS2010) tells me:

error C2248: 'MyNamespace::Container::value' : cannot access private member declared in class 'MyNamespace::Container'

Does anyone have any idea what I'm missing?

4

2 回答 2

1

根据我的评论,如果您声明friend类似,它将起作用:

friend Type AccessPrivateImplementation::getValue<>(Container<Type>* volume);
                                                 ^^
于 2013-04-30T19:53:20.610 回答
1

类模板中的friend声明声明了一个位于命名空间中Container的友元非模板函数。getValue()AccessPrivateImplementation

但是,您还没有提供这样的功能。相反,您在AccessPrivateImplementation命名空间中拥有的是一个函数template,您希望成为其适当的专业化friendContainer<T>对于给定的T)。

为此,您需要的声明是:

friend Type AccessPrivateImplementation::getValue<>(Container<Type>* volume);
//                                               ^^

这是一个实时示例,显示了使用上述修复程序编译的代码。

于 2013-04-30T19:50:28.940 回答