c++ - 具有嵌套命名空间内友元函数的模板类

标签 c++ templates namespaces friend

我正在尝试创建一个带有友元函数的模板类,该函数位于嵌套的命名空间内。如果我删除所有 namespace 或删除所有模板化,它工作正常。但是两者都到位了,它不会编译。让我们看一些代码:

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;
}

编译器 (VS2010) 告诉我:

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

有人知道我错过了什么吗?

最佳答案

friend Container 内的声明类模板声明了一个 friend 非模板函数getValue()住在AccessPrivateImplementation命名空间。

但是,您还没有提供这样的功能。相反,您在 AccessPrivateImplementation 中拥有的内容命名空间是一个函数模板,您希望对其进行适当的特化friendContainer<T> (对于给定的 T )。

为此,您需要的声明是:

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

这是一个live example显示您的代码使用上述修复进行编译。

关于c++ - 具有嵌套命名空间内友元函数的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16307836/

相关文章:

c++ - 在 Ubuntu 13.10 x64 C++11 中创建 std::threads 时出错

c++ - 编译时数学函数的 constexpr vs 模板?

c++ - 范围解析::嵌套模板类型名

c++ - 二维点数据集中的 OpenCV 模板

php - 在 if/else 语句中使用命名空间

c++ - matPutVariable: error (matrix::serialize::WrongSize) 试图输出数据到mat文件

c++ - 我如何转发声明已经过 typedef 的类?

ruby - 如何在有前缀但没有 namespace 的节点上使用 xpath?

c++ - 在C++中,一个线程中的new是否可以分配另一个线程删除的内存?

c++ - 使用命名空间标准?