考虑以下代码片段。
template <T>
MyPtr<T> CreateObject()
{
// Do something here first...
// return our new object
return MyPtr<T>(new T());
}
class Foo
{
private:
Foo() { }
public:
static MyPtr<Foo> GetNewInstance()
{
// ERROR: Foo is private...
return CreateObject<Foo>();
}
};
class Bar
{
public:
Bar() { }
};
int main()
{
MyPtr<Bar> bar = CreateObject<Bar>();
return 0;
}
如果不为 CreateObject 使用宏(我喜欢 MyPtr<type> obj = CreateObject<type>(params)
的语法),有没有办法让函数 CreateObject 与调用函数共享相同的上下文,从而能够访问私有(private) Foo c'tor? “ friend ”不是我要找的,因为这意味着任何调用 CreateObject 的人都可以访问私有(private) Foo c'tor,这不是我想要的。重载 new 运算符也不起作用,因为必须返回 MyPtr 而不是仅返回 T*(通过将 T* 分配给 MyPtr 将类型分配给其他地方所需的对象)。
我想我正在寻找的是介于宏和模板函数之间的东西(模板函数的语法,但像宏一样完全展开)。在这种特殊情况下拥有此功能将非常有用。
最佳答案
好吧,你可以用 passkey pattern 来做到这一点:
template<class T, class PassKey>
MyPtr<T> CreateObject(PassKey const& key)
{
return new T(key);
}
class FooKey{
private:
FooKey(){} // private ctor
FooKey(const FooKey&); // undefined private copy ctor
friend class Foo;
};
class Foo{
public:
// public ctor
Foo(FooKey const&){}
static MyPtr<Foo> GetNewInstance()
{
return CreateObject<Foo>(FooKey());
}
};
在 C++0x 中,这比每次都创建一个新的 Key
结构要容易得多,因为现在允许模板参数成为 friend
:
template<class T>
struct PassKey{
private:
PassKey(){}
PassKey(const PassKey<T>&);
friend T;
};
关于c++ - 具有调用者上下文的模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578985/