Cryptography Man
Cryptography Man

Reputation: 209

Static variable across templated function compilations

When creating a templated function, each template is its own independent version. As such, the static variables will only be static with respect to the function that calls it.

What are some efficient ways to get around this while still keeping that data private to the function, especially for a function in a header/inlined function?

I was thinking something along these lines, but it's private to the file then:

namespace
{
    unsigned char none;
}

template< typename t > unsigned char foo( )
{
    return none;
}

Upvotes: 0

Views: 76

Answers (2)

llllllllll
llllllllll

Reputation: 16404

In C++17, I would recommend inline variable, so you can keep it in header and avoid duplicate symbols:

inline class cfoo_internal {
    unsigned char none /* = initialize */;
    template< typename t > friend unsigned char foo();
} foo_internal;

template< typename t > unsigned char foo( )
{
    return foo_internal.none;
}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206577

You can use the following strategy:

  1. Call a regular function in the implementation of the function template.
  2. Store the data as a static variable in the regular function.

Something along the lines of:

unsigned char foo_impl()
{
   static unsigned char none = <some initializer>;
   return none;
}

template< typename t > unsigned char foo( )
{
    return foo_impl();
}

You can implement foo_impl in a source file instead of a header file in case there is a need to encapsulate its implementation.

Upvotes: 3

Related Questions