I think you're on the right track.
The trick is this: in any translation unit, do not create a template before your specialization.
For instance:
// test.h #ifndef TEST_H #define TEST_H template <typename T> extern int variable; template <> extern int variable<char>; template <> extern int variable<int>; #endif // TEST_H
Then:
// test2.cpp #include "test.h" template <> int variable<char> = 23; template <> int variable<int> = 24;
And finally:
// test.cpp
For me, these outputs are:
23 24
Update
TC points out in the comments below that specializations must be declared before first use, so I updated "test.h" above to do this.
Update 2
There seems to be some divergence of implementation. clang seems to handle this penalty:
template <typename T> extern int variable; template <> extern int variable<char>; template <> extern int variable<int>; #include <iostream> int main() { std::cout << variable<char> << '\n'; std::cout << variable<int> << '\n'; } template <> int variable<char> = 23; template <> int variable<int> = 24;
http://melpon.org/wandbox/permlink/DGYKvvoPbmRIHaFi
However, gcc gives an error:
prog.cc:4:13: error: explicit template specialization cannot have a storage class template <> extern int variable<char>; ^~~~~~ prog.cc:5:13: error: explicit template specialization cannot have a storage class template <> extern int variable<int>; ^~~~~~
I searched the standard and a list of the main problems, and I can not find anything to indicate that one compiler or the other is correct. If someone sees such evidence, I will gladly include it in this answer.
source share