It is not possible to declare a template variable without defining it.

I want to send the declaration of template variables to the header file, and then have the actual instances in a separate compiler.

I am fortunate that C ++ 14 variable templates work very similar to static class variables. Unfortunately, this does not seem to be quite true, and this prevents me from sending my template variables.

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 sample code above compiles and runs as-is under GCC. But no wonder line 10 gives a compile-time error:

 specialization of 'variable<char>' after instantiation template <> int variable<char> = 23; ^ 
+5
source share
1 answer

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 #include "test.h" #include <iostream> int main() { std::cout << variable<char> << '\n'; std::cout << variable<int> << '\n'; } 

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.

+1
source

Source: https://habr.com/ru/post/1241338/


All Articles