c++ - Static variable initialization for template specialization in header -
there c++ header library, @ point there has been added template specialization (right in header). good, until required link 2 files used library. of course, there linker error. problem library's classes use static variables. initialized template specialization directly in header file.
the question is: possible initialize static variable in header file template specialization , somehow avoid linking error? (something add inline keyword template class method specialization similar linking problem.)
any ideas welcome (including dirty tricks etc).
some code example:
lib.hpp:
template <typename t> struct libclass { static const int variable; static void f() { // use variable } }; typedef libclass<int> intlibclass; template <> const int intlibclass::variable = 0; typedef libclass<double> doublelibclass; template <> const int doublelibclass::variable = 1;
a.cpp:
#include "lib.hpp" void g() { intlibclass a; a.f(); }
b.cpp:
#include "lib.hpp" void h() { doublelibclass b; b.f(); } int main() { h(); }
and want link , b together.
g++ a.cpp b.cpp
simply add project additional file lib.cpp
following contents:
#include "lib.hpp" template <> const int intlibclass::variable = 0; template <> const int doublelibclass::variable = 1;
and change lib.hpp
file in following way (remove initialization):
typedef libclass<int> intlibclass; template <> const int intlibclass::variable; typedef libclass<double> doublelibclass; template <> const int doublelibclass::variable;
as johannes schaub - litb noted in comments solution implies no initialization of static variable in header file (as required in question), variable value can not used in constant expressions (outside of lib.cpp
file).
but solution appropriate code snippets given in question.
Comments
Post a Comment