c++ - Is there a way to call an initialization function only when specific class template (specialization) is instantiated? -
i'm designing wrapper on various computational functionality. of underlying backends require init functions called before other api calls made. use static variable initialized before main, , wrap in function described here can catch errors produced during initialization.
i wonder if there better way handle this. note there never instance of class template, either typedef or static member.
to address problem of initializing api specializations, , of initializing once, i'd this:
#include <iostream> template <typename t> struct wrapper { // class statically instantiated struct ctorclass { ctorclass() { std::cout << "init\n"; } }; static ctorclass static_ctor; static void compute1(){} static void compute2(){} }; // definition template static member cons template <typename t> typename wrapper<t>::ctorclass wrapper<t>::static_ctor; struct needinit{}; // have use static_ctor in every funcition of template <> void wrapper<needinit>::compute1() { static_ctor; } template <> void wrapper<needinit>::compute2() { static_ctor; } int main() { wrapper<int>::compute1(); wrapper<int>::compute2(); wrapper<needinit>::compute1(); wrapper<needinit>::compute2(); }
sadly, way have use static_ctor
in every function specialization belongs wrapper<needinit>
class. wouldn't need check initialization have been called.
then, catch errors said.
Comments
Post a Comment