If I template a function in C++ on the return type:
template<class T> T foo(int x) { };
I can use explicit template specialization to create a double instance:
template<> double foo<double>(int x) { };
I tried to use forward declaration to create an instance of an undefined struct:
struct bar;
template<> bar foo<bar>(int x) { }
This fails with error: return type ‘struct bar’ is incomplete. I thought this would be allowed, even after reading the accepted answer on When to use forward declaration? since, until I create an instance of foo<bar>, the explicit templated code is never created. Clearly this is not the case (why not?).
Is it possible to have code for functions whose type might not exist at compile time, and only compile the code if the particular explicit specialization is instanced? The motivation for this is an “overloaded” struct reader, where the overload operations are procedurally generated before the compile (via a script).
When you define an specialization of a function you are defining the function, not a function template. The rules at this point are exactly the same as for any regular function and because you are using the type in a way that needs a complete type, the lack of a definition for
barmakes your program ill-formed.(The lack of a return statement also makes the program ill-formed…)