Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of std::is_const for references to const?

Consider the code:

int const  x = 50;
int const& y = x;
cout << std::is_const<decltype(x)>::value << endl; // 1
cout << std::is_const<decltype(y)>::value << endl; // 0

This makes sense, because y is not a const reference, it is a reference to a const.

Is there a foo such that std::foo<decltype(y)>::value is 1? If not, what would it look like to define my own?

like image 849
Claudiu Avatar asked Jun 12 '15 15:06

Claudiu


People also ask

How do you reference a const?

You can declare the test function as: int test(gadget const &g); In this case, parameter g has type “reference to const gadget .” This lets you write the call as test(x) , as if it were passing by value, but it yields the exact same performance as if it were passing by address.

How do you declare a const reference in C++?

A variable can be declared as a reference by putting '&' in the declaration. int i = 10; // Reference to i. References to pointers is a modifiable value that's used same as a normal pointer.

Is const reference an lvalue?

By using the const keyword when declaring an lvalue reference, we tell an lvalue reference to treat the object it is referencing as const. Such a reference is called an lvalue reference to a const value (sometimes called a reference to const or a const reference).

Is const reference type?

Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const. Indeed, because there is no way to make a reference refer to a different object, in some sense all references are const.


1 Answers

Use remove_reference:

#include <string>
#include <iostream>
#include <type_traits>
using namespace std;

int main()
{
    int const  x = 50;
    int const& y = x;
    cout << std::is_const<std::remove_reference<decltype(x)>::type>::value << endl; // 1
    cout << std::is_const<std::remove_reference<decltype(y)>::type>::value << endl; // 1

    return 0;
}

See on coliru

like image 145
Borgleader Avatar answered Nov 12 '22 21:11

Borgleader