简体   繁体   中英

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. 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.

new T() returns T* , so your Generate function should look like:

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

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

This function must also be public if you'd like to call it outside the class.

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* . You probably want to change the return type to T* . Accordingly, you must assign the returned type to a T* variable. Since your T is B* , that variable must have the type B** .
  2. You try to call a non-static member of A without an instance. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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