Reputation: 31911
How can I define a static member variable that is also thread local inside a template class? I think I've figured out how to do it in GCC, but would like to confirm this will work correctly in terms of linking, initialization and resolution. Also the translation to another compiler would be helpful (like MSVC) so I can get a nice macro to do this.
template<typename T>
class my_class
{
struct some_type { };
static __thread some_type * ptr;
};
template<typename T>
__thread typename my_class<T>::some_type * my_class<T>::ptr = 0;
An alternate way to achieve the same thing would also be okay (that is, to use a distinct thread local per template instance).
Upvotes: 6
Views: 2838
Reputation: 76805
I believe your code is correct, and would translate in MSVC by replacing __thread
by __declspec(thread)
(see Thread Local Storage on MSDN) :
template<typename T>
class my_class
{
struct some_type { };
static __declspec(thread) some_type * ptr;
};
template<typename T>
__declspec(thread) typename my_class<T>::some_type * my_class<T>::ptr = 0;
Upvotes: 2