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?
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.
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.
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:
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).
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)
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.
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