I was writing a test for my iterator types and wanted to check that the reference returned by de-referencing iterators provided by begin()
and cbegin()
are non-const and const respectively.
I tried doing something similar to the following : -
#include <type_traits>
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{0};
std::cout << std::is_const<decltype(*vec.begin())>::value << std::endl;
std::cout << std::is_const<decltype(*vec.cbegin())>::value << std::endl;
}
But this prints 0
for both cases.
Is there a way to check if a reference is const?
I can use C++11/14/17 features.
The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.
A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.
Once a reference variable has been defined to refer to a particular variable it can refer to any other variable. A reference is not a constant pointer.
A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const. Once a reference is bound to refer to an object, it can not be bound to refer to another object.
Remove the reference to get the referenced type to inspect its constness. A reference itself is never const - even though references to const may colloquially be called const references:
std::is_const_v<std::remove_reference_t<decltype(*it)>>
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