Question

There's this standard way for checking whether types match:

template<class T, class U>
struct is_same { static const bool value = false; };

template<class T>
struct is_same<T, T> { static const bool value = true; };

And I use it like this:

if (SamTypeCheck<double,double>::value)
    cout<<"same"<<endl;
else
    cout<<"different"<<endl;

if (SamTypeCheck<int,double>::value)
    cout<<"same"<<endl;
else
    cout<<"different"<<endl;

This looks to me not thread safe since it uses static member variables. Is it really not thread safe? The code confused me somehow. What's the replacement to that to have something thread safe with the same functionality?

Why do I need this?

I have a templatized class for dealing with matrices, and I want to use the Intel Compiler Math Kernel Library for matrix multiplication and inversion, in which the function is different for every type, so I have to know the type before performing the matrix operation.

Thank you.

Was it helpful?

Solution

This looks to me not thread safe since it uses static member variables.

It uses static constant member variables ("constant variables"... ^^ let's say "static member constants"). What is often said as "not thread safe" is static mutable variables ("mutable" meaning "non-const", not necessarily defined with the keyword mutable).

You can sometimes see code with enum { value = 0 }; (or 1) instead of static const bool value = false; (or true), but it's often considered a "hack" and you lose the bool type.

Also, in C++11, use std::is_same from the header <type_traits> directly.

OTHER TIPS

As previously stated in a comment, these are all compile time checks, so thread safe is not an issue. Saying that, you should always use inheritance in type checks because it is a better/more elegant design (followed by the standard library implementations)

Something like

 template<typename U, typename T> struct is_same : public std::false_type {};
 template<typename T> struct is_same<T, T> : public std::true_type {};

std::true/false type contains std::integral_constant "value"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top