c++ - 具有调用者上下文的模板函数?

标签 c++

考虑以下代码片段。

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

Example at Ideone .

在 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/

相关文章:

c++ - 在 C++ 中使用枚举值作为映射中的条目

c++ - 如何编写eclipse插件格式化C++14源码?

c++ - 接近矩形的轮廓

c++ - lambda 函数的静态数组 (C++)

C++ - 虚拟析构函数和链接器错误

c++ - 如果我在 C++ 中使用内联函数,为什么会重新定义“template<class T>”?

c++ - 为什么标准库假定它在全局命名空间中?

C++ 可以有条件地向下转换类指针吗?

c++ - 如何使用递归反转打印堆栈?

c++ - 存储成员函数模板实例时出错