I am trying to disallow a specific operation on volatile types. To accomplish this I am trying to use std::is_volatile
, but the code below is compiling without errors, which is not what I want.
Why is is_volatile::value
false in the case below?
#include <type_traits>
template<typename T>
inline void DoStuff(T val) {
static_assert(!std::is_volatile<T>::value, "No volatile types plz");
//...
}
int main() {
volatile char sometext[261];
DoStuff(sometext);
}
The problem is that T isn't a volatile
type at all. It's volatile char*
. Wait a minute, you say, I see volatile
right there. True, but consider this: char* volatile
is a volatile type. volatile char*
isn't. It's a non-volatile pointer to a volatile char
array.
Solution: std::is_volatile<typename std::remove_pointer<T>::type>
When trying to pass the array by value, it decays into a pointer to its first element.
This means that val
is actually a int volatile *
. As such, it points to a volatile int
, but is not itself volatile. Hence, std::is_volatile
returns false.
You may try taking in the array by reference, or using std::remove_pointer
.
Because the functions accepts its argument by value, the cv-qualification of the original argument is lost.
Accept it by reference:
void DoStuff(T& val)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With