template function in struct

Hi All,

I understand template functions and how to call them explicitly when no arguments are passed to them but can't seem to instantiate them explicitly when it resides within a class or struct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Creator
{

   template <class T>
   T * New(T * p)
   {
      return new T;
   }

};


Creator cr;
MyClass * pMy = cr.New<MyClass>();     //gives compile error 


The compiler complains about MyClass (or any other) being used illegally in expression ...

Can someone please explain how this can be done.
You didn't pass the function argument.
Hi Peter - I made a mistake its supposed to be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Creator
{

   template <class T>
   T * New()
   {
      return new T;
   }

};


Creator cr;
MyClass * pMy = cr.New<MyClass>();     
Has the MyClass class been defined?
There are a lot of great features in C++11, but unique_ptr stands out in the area of code hygiene. Simply put, this is a magic bullet for dynamically created objects. It won't solve every problem, but it is really, really good at what it does: managing dynamically created objects with simple ownership semantics.
http://www.drdobbs.com/cpp/c11-uniqueptr/240002708


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <memory>

namespace creator
{
    template < typename T, typename... ARGS >
    std::unique_ptr<T> make_unique( ARGS&&... args )
    { return std::unique_ptr<T>( new T( std::forward<ARGS>(args)... ) ) ; }
}

int main()
{
    struct A
    {
        A() { std::cout << this << " - A::default_constructor\n" ; }

        A( int i, double d = 2.3, const char* cstr = "hello" )
        { std::cout << this << " - A::A( " << i << ", " << d << ", '" << cstr << "' )\n" ; }

        ~A() { std::cout << this << " - A::destructor\n" ; }
    };

    auto pa1 = creator::make_unique<A>() ;
    auto pa2 = creator::make_unique<A>(1) ;
    auto pa3 = creator::make_unique<A>( 22, 33.44 ) ;
    auto pa4 = creator::make_unique<A>( 333, 555.666, "bye" ) ;

    std::cout << "\nexit main\n\n" ;
}

http://coliru.stacked-crooked.com/a/185b87d75f94d6ab

Note: std::make_unique<>() (C++14)
http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique
@Peter87: Yes - MyClass has been defined.

@JLBorges: thanks for the reply - I however note the make_unique template in your sample above resides within the namespace creator.

Can this creator be a class or struct instead of a namespace?
> Can this creator be a class or struct instead of a namespace?

Yes.

But is an object really required?
Topic archived. No new replies allowed.