2

i wanted to create a template class with a static function

template <typename T>
class Memory
{
 public:
  template < typename T>
  static <T>* alloc( int dim )
  {
    T *tmp = new T [ dim ];
    return tmp;
  };
}

but i will always get

int *a = Memory::alloc<int>(5)

i dont know what to chance..

 »template<class T> class Memory« used without template parameters
 expected primary-expression before »int«
 Fehler: expected »,« or »;« before »int«
2
  • i dont compile,the last codebox is the problem :) Commented Apr 28, 2012 at 12:55
  • @Tudor: Given that the OP has posted a compiler error message, presumably not! Commented Apr 28, 2012 at 12:55

1 Answer 1

6

You're templating both the class and the function, when you likely only want to template one of them.

Is this what you mean?

template <typename T>
class Memory
{
 public:
  static T* alloc( int dim )
  {
    T *tmp = new T [ dim ];
    return tmp;
  };
}

int *a = Memory<int>::alloc(5);

Here's a correct version with both:

template <typename T>
class Memory
{
 public:
  template <typename U>
  static U* alloc( int dim )
  {
    U *tmp = new U [ dim ];
    return tmp;
  };
}

int *a = Memory<float>::alloc<int>(5);

You can remove the outer template if you just want the function to be templated.

Sign up to request clarification or add additional context in comments.

2 Comments

ahh oki, so is it possible to make the funktion with template<typename T> static T* alloc ... ?
@Roby I don't fully understand what you mean but I've updated the post with another example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.