Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is volatile not compiling with std::min

Tags:

c++

gcc

volatile

Why is following code not compilable (gcc-5.4.0)?

volatile int i{100};
int j{200};
std::cout << std::min(i, j);

I mean I see the compiler error:

error: no matching function for call to ‘min(volatile int&, int&)’

Isn't volatile just hint to compiler, that the variable could change from outside of the program?

std::min(int(i), j);

Is of course working. But shouldn't original work too?

like image 824
Libor Tomsik Avatar asked Nov 28 '17 11:11

Libor Tomsik


People also ask

What is the use of volatile in C++?

A type qualifier that you can use to declare that an object can be modified in the program by the hardware. You can use the /volatile compiler switch to modify how the compiler interprets this keyword. Visual Studio interprets the volatile keyword differently depending on the target architecture.

How to get type T with volatile qualification in C++ STL?

The std::add_volatile template of C++ STL is used to get the type T with volatile qualification. The function std::is_volatile is used to check if type T is volatile qualified or not.

Why is the result of std::min by reference dangling?

Capturing the result of std::min by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned:

Is the C++11 ISO standard volatile keyword different in MSVC?

If you are familiar with the C# volatile keyword, or familiar with the behavior of volatile in earlier versions of the Microsoft C++ compiler (MSVC), be aware that the C++11 ISO Standard volatile keyword is different and is supported in MSVC when the /volatile:iso compiler option is specified. (For ARM, it's specified by default).


2 Answers

volatile is a qualifier just like const. It's more than a mere hint to the compiler.

std::min expects the two parameters to have exactly the same types and qualifiers. So in your case it issues a diagnostic.

Since you are allowed to introduce qualifiers, you could indulge in a little hand-holding and write

std::min<volatile int>(i, j)
like image 54
Bathsheba Avatar answered Oct 28 '22 16:10

Bathsheba


As @Bathsheba pointed out, type deduction on the two arguments must give the same type.

But for the sake of completeness std::min is also overloaded to accept a std::initializer_list. The elements of it are subject to copy initialization, so top level cv-qualifiers are immaterial. So this will work:

std::cout << std::min({i, j});

Just bear in mind that it performs copies, and doesn't accept or return references.

like image 32
StoryTeller - Unslander Monica Avatar answered Oct 28 '22 16:10

StoryTeller - Unslander Monica