Floogle wrote:
On 6 Jan 2006 05:46:19 -0800, "Neelesh Bodas"
<ne***********@gmail.com> wrote:
Stephane Wirtel wrote: Can you try with typename ?
class MyClass {
public:
template <typename T> T * createAnInstance () {
return new T ();
}
};
typename and class are synonyms when used inside <>s after the keyword
"template". So that should not solve the problem (if there was a
problem at first place)
To the OP - The code in your post compiles well on Comeau online. May
be the problem lies with your compiler.
I'm using MSVC6... :o(
VC6 is known to have many template problems. You can consult the MS
newsgroups for more details, but one solution is to convert the
template type specification to automatic type deduction through
overloading by using this trick from _Modern C++ Design_:
template<typename T>
struct Type2Type { typedef T Type; };
class MyClass
{
public:
template <class T>
T* CreateAnInstance( Type2Type<T> )
{
return new T();
}
};
int main()
{
MyClass mc;
int* i = mc.CreateAnInstance( Type2Type<int>() );
return 0;
}
You might also make MyClass::CreateAnInstance() either static or const,
depending on what your real code does. Also, you might consider using
returning a smart pointer (e.g., std::auto_ptr) rather than a raw
pointer to help prevent leaks:
#include <memory>
using namespace std;
class MyClass
{
public:
template <class T>
static auto_ptr<T> CreateAnInstance( Type2Type<T> )
{
return auto_ptr<T>( new T() );
}
};
Cheers! --M