In Memory.h I have:
#pragma once
class Memory
{public:
template <typename T, typename ... TArgs>
static T* newAlloc(TArgs ... args)
{
return new T(args ...);
}
};
And in main.cpp I have:
#include "Memory.h" // The template class is defined here
class Foo
{public:
Foo(int a, const char* c) {}
};
int main()
{
Memory::newAlloc<Foo>(7, "str");
}
And this compiles fine even though Foo isn't fully defined until after I pasted in Memory.h. I'm confused about why this compiles. Isn't it true the equivalent code after the compiler has pasted in Memory.h is like this in main.cpp:
class Memory
{
public:
static Foo* newAlloc(int a, const char* c)
{
return new Foo(a, c);
}
};
class Foo
{public:
Foo(int a, const char* c) {}
};
int main()
{
Memory::newAlloc(7, "str");
}
??? Because this doesn't compile, I get the error:
'newAlloc' identifier not found 'newAlloc' is not a member of Memory
Basically it wants the full definition of Foo. If I place the Foo class definition above the Memory one it then compiles fine. So given that my second version is the equivalent of code after template instantiation (is it?) then why does the first version compile but the second not?
I am on Visual Studio 2019 16.4.5
No, it isn't true. This would be equivalent:
You'll find that this compiles.
It works because
Foo
is defined before the template is instantiated withFoo
as template argument.