Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check whether a reference is const?

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.

like image 328
flau Avatar asked Nov 23 '18 10:11

flau


People also ask

Are references const?

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.

Is a reference a const pointer?

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.

Can reference variables be constant?

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.

What is the difference between const reference and reference?

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.


1 Answers

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)>>
like image 197
eerorika Avatar answered Sep 27 '22 23:09

eerorika