Reputation: 209
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
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
Reputation: 206577
You can use the following strategy:
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