I am wanting to forward declare variable templates in a header file, and then have the actual instantiations in a separate compilation unit.
I was led to believe that C++14 variable templates operated very much like static class variables do. This is unfortunately seeming not to be quite the case, and it is preventing me from forward declaring my variable templates.
template <typename T> struct Variable {
static int variable;
};
template <typename T>
extern int variable;
int main() {
(void) Variable<char>::variable;
// (void) variable<char>; // <-- line 10
}
template <> int Variable<char>::variable = 42;
template <> int variable<char> = 23;
The code sample above compiles and runs as-is under GCC. But uncommenting line 10 gives a compile-time error:
specialization of 'variable<char>' after instantiation
template <> int variable<char> = 23;
^
I think you're on the right track.
The trick is this: In any one translation unit, don't instantiate the template prior to your specialization.
For example:
Then:
And finally:
For me this outputs:
Update
T.C. points out in the comments below that the specializations need to be declared before first use, so I've updated "test.h" above to do that.
Update 2
There seems to be some implementation divergence. clang appears to handle this fine:
http://melpon.org/wandbox/permlink/DGYKvvoPbmRIHaFi
However gcc gives an error:
I've searched the standard and the Core Issues list, and I can't find anything to indicate one compiler or the other is correct. If someone does see such evidence, I'm happy to include it in this answer.