简体   繁体   English

C ++模板语法-使用指针分配类型

[英]C++ templating syntax - allocate type with pointer

How can I do memory allocation like this: 我该如何进行内存分配:

template <class T>
class A
{
  T Generate()
  {
    return new T();    // Error
  }
};

A<B *> a;
B * pI = A.Generate();

Or can you only ever define something as: 或者您只能将以下内容定义为:

A<B> a;

If I understood you correctly you wish to have specialization of A for pointer types. 如果我对您的理解正确,则希望对指针类型使用A的特殊化。 Try something like: 尝试类似:

#include <cstdio>

template <class T>
class A
{
public:
  T *Generate()
  {
    printf("A\n");
    return new T;    // Error
  }
};

template <class T>
class A<T*> {
public:
  T *Generate() {
    printf("Specialization of A\n");
    return new T;
  }
};

class B {
};

int main() {
   A<B *> a;
   B * pI = a.Generate();
}

Edit: 编辑:

To "override" only a part of the functionality: 要“替代”功能的仅一部分:

template <class T>
class Generator
{
public:
  T *Generate()
  {
    printf("Generator\n");
    return new T;    // Error
  }
};

template <class T>
class Generator<T*> {
public:
  T *Generate() {
    printf("Specialization of Generator\n");
    return new T;
  }
};

template <class T>
class A: public Generator<T>
{
public:
  // does some other stuff
};

You have a bunch of issues with your code: 您的代码有很多问题:

A.Generate() should be a.Generate() as Generate is a member function. A.Generate()应该是a.Generate()因为Generate是成员函数。

new T() returns T* , so your Generate function should look like: new T()返回T* ,因此您的Generate函数应类似于:

T* Generate()
{
   return new T();
}

This should also be reflected in your usage: 这也应反映在您的用法中:

A<B *> a;
B ** pI = a.Generate(); //generator for B* returns B**

new will return a pointer so you need the signature new将返回一个指针,因此您需要签名

T* Generate()
{
    return new T();
}

This function must also be public if you'd like to call it outside the class. 如果您想在课程之外调用此函数,则该函数也必须是public的。

How can I do memory allocation like this 我该如何进行内存分配

By fixing the syntax and semantic errors. 通过修复语法和语义错误。

  1. Return type of Generate is T , yet you return T* . Generate返回类型为T ,但您返回T* You probably want to change the return type to T* . 您可能想将返回类型更改为T* Accordingly, you must assign the returned type to a T* variable. 因此,必须将返回的类型分配给T*变量。 Since your T is B* , that variable must have the type B** . 由于您的TB* ,因此该变量必须具有类型B**
  2. You try to call a non-static member of A without an instance. 您尝试调用的非静态成员A没有实例。 Call the member using the instance instead. 而是使用实例调用成员。 Also, that member is private. 另外,该成员是私人的。 Make it public. 公开。

When you've fixed the code, you'll see that it does memory allocation successfully. 修复代码后,您会看到它成功完成了内存分配。

Or can you only ever define something as: 或者您只能将以下内容定义为:

A<B> a;

No, there are many more ways to define something. 不,还有更多定义方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM