c++ - Partial Specialization for an Integral Constant vs a Type -
is possible specialize template based on whether template argument either type or integral constant? here's example doesn't compile illustrates intent:
#include <cstdio> #include <cstddef> // tag struct struct dynamicsize {}; template<class t, class size> class container; template<class t> class container<t, dynamicsize> { public: container() { std::puts("dynamic size"); } }; template<class t, int size> class container<t, size> { public: container() { std::puts("static size"); } }; int main(int argc, char* argv[]) { container<char, 20> a; container<char, dynamicsize> b; }
the eigen library has support matrices of fixed size or runtime determined size , similar this. implementation there template argument integral constant , dynamic tag constant equal -1 i'm curious if there's way.
i think way have container
template take type parameter size
. it's responsibility of type handle whether it's dynamic or static. i'm thinking details specific type of storage type confined struct
types. perhaps following example helpful.
example code
#include <iostream> struct dynamicsize { static const int size = -1; }; template<int size> struct fixedsize { static const int size = size; }; template<class t, class size> class container { public: container() { std::cout << size::size << "\n"; } }; int main() { container<char, fixedsize<20>> a; container<char, dynamicsize> b; return 0; }
example output
20 -1