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