C++ Logo

std-discussion

Advanced search

Re: How to force initialization of templated static variable in instantiated template?

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Thu, 21 Jul 2022 21:57:27 +0100
On Thu, 21 Jul 2022 19:30:56 +0000
Marios Staikopoulos via Std-Discussion
<std-discussion_at_[hidden]> wrote:

> Hi, I am attempting to initialize a static runtime variable that is
> initialized in every class via a member static variable that is
> in-turn initialized via a static dispatcher function.
>
> For the most part, everything works - but I have encountered an
> unexpected caveat - the static variable of a template is not
> initialized on template instantiation, only on access of the internal
> variable. This is something I want to be done automatically so that
> you do not have to do any additional instantiation work for every
> possible template variant used in code...
>
> An example of this attempt can be seen here:
> https://godbolt.org/z/Mb3hr576z
>
> Currently, the only two ways I can think of are shown in the example
> below: (1) manually touch the static member in any code
> (2) same as 1, but we simply touch it in the default constructor
>
> However, both examples require code modification *outside* of the
> STATIC_BODY macro. I would like to constrain it to be within if
> possible.
>
> Is anyone aware of any techniques/compiler that can be used to force
> to initialize templated statics on initialization?

Hi,

I'm not sure what exactly is your goal, but here is my approach,
although it changes the interface.

https://godbolt.org/z/9ve7saerM

Here I don't have dispatchers, I just define the body inline that I want
to run before main on instantiation of the type. It requires static
inline variables, therefore C++17. I had a similar approach for solving
it with your interface, but MSVC didn't cooperate.

Cheers,
Lénárd

Received on 2022-07-21 20:57:33