How do I check whether a reference is const?

  • A+
Category:Languages

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.

 


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)>> 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: