Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::is_volatile?

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);
}
like image 824
MathuSum Mut Avatar asked Oct 05 '17 09:10

MathuSum Mut


3 Answers

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>

like image 177
MSalters Avatar answered Oct 19 '22 22:10

MSalters


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.

like image 9
Quentin Avatar answered Oct 20 '22 00:10

Quentin


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)
like image 1
Maxim Egorushkin Avatar answered Oct 19 '22 23:10

Maxim Egorushkin