在 Linux 上使用 GCC 4.8.2,我想授予工厂方法 Create() 访问类 C 的私有(private)构造函数的权限,但在尝试声明时出现“错误:‘Create’未在此范围内声明”一个专业的 friend 。如何在不向 B::Create() 的所有类型开放声明的情况下使其工作?
template <typename T> class A {
public:
class B;
template <typename U> class C;
};
template <typename T>
class A<T>::B {
public:
template <typename U> static void Create();
};
template <typename T> template <typename U>
class A<T>::C {
C() = default;
friend void B::Create<U>();
};
template <typename T> template <typename U>
void A<T>::B::Create() {
C<U>{};
}
int main() {
A<int>::B::Create<char>();
}
最佳答案
我认为您遇到了编译器缺陷。以下代码仅使用一层模板,在 g++ 4.8.2 中运行良好。
class Foo
{
public:
template <typename U> static Foo* Create();
};
template <typename U> class Bar : public Foo
{
private:
Bar() = default;
friend Foo* Foo::Create<U>();
};
template <typename U>
Foo* Foo::Create() {
return new Bar<U>();
}
但是,同一个编译器无法编译您的代码。我认为您已经尝试过的一种解决方法是替换
friend B* B::Create<U>();
与
template <typename V>
friend B* B::Create<V>();
关于c++ - 要将嵌套类中定义的静态模板函数声明为兄弟嵌套类中的友元,必须做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28643305/