c++ - 模板类的对象创建包装器

标签 c++ templates

给定一个模板类:

template <typename TYPE>
class SomeClass {
 public:
  typedef boost::intrusive_ptr<SomeClass<TYPE> > Client_t;
  inline Client_t GetClient() { return Client_t(this); }
};

SomeClass 只能通过 SomeClass::GetClient() 返回的指针引用使用。这使得像这样围绕创建编写包装函数变得很自然:

template <typename TYPE>
SomeClass<TYPE>::Client_t New_SomeClass() { 
  return (new SomeClass<TYPE>)->GetClient(); 
}

在 GCC 4.4 下编译以上代码:

SomeClass<int>::Client_t some_class = New_SomeClass();

给出错误“'New_SomeClass' was not declared in this scope”

现在我不是模板向导,所以这里可能有我不知道的细节,但我猜我根本不能使用这种构造,因为 C++ 不允许重载返回类型。

我想一个...shiver...宏可以解决它:

#define NEW_SOMECLASS(TYPE) ((new SomeClass<TYPE>)->GetClient())

auto some_class = NEW_SOMECLASS(int);

但必须有一种明智的方法来公开模板类的对象创建,而无需诉诸宏或其他繁琐的构造?

最佳答案

SomeClass<int>::Client_t some_class = New_SomeClass<int>();

因为 New_SomeClass 的模板参数不依赖于函数参数,所以您必须指定它们。但是,您报告的错误消息对于这个问题有点奇怪,因此您可能遇到了其他问题。

或者,我的偏好而不是 New_SomeClass 函数:

template<class T>
struct SomeClass {
  typedef boost::intrusive_ptr<SomeClass> Client;
  inline Client client() { return Client_t(this); }

  static Client create() { return (new SomeClass())->client(); }

private:
  SomeClass(); // can be public too, if you really need it accessible
};

//...
SomeClass<int>::Client some_class = SomeClass<int>::create();

尽管它本质上只是将函数“移入”类中,但我发现它通常更简洁。

无论如何,如果您的编译器支持 0x 的“auto”,那么您可以使用它:

auto some_class = SomeClass<int>::create();

关于c++ - 模板类的对象创建包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2100012/

相关文章:

c++ - 学习 C++,我不知道我在这里做错了什么

c++ - SDL/C++ 没有音频

c++ - 从依赖基类访问类型

c++ - Variadic 模板元编程 : a bug in clang++ or g++?

c++ - 静态成员函数,名称相同,代码不同,只使用第一个遇到的版本,这是为什么?

c++ - boost::iostream readline 在 4096 字节后停止

c++ - 在模板类中实现和调用静态方法

c++ - 如何将 std::transform 与模板一起使用

templates - 在你的 go 二进制文件中包含模板/html 文件

c# - 在 Visual Studio C++ 中使用 DLL