Is it possible to convert the is_const expressions into a test function or is this impossible because top level cv-qualifieres are ignored during template type deduction?
int main()
{
using std::is_const;
const int x = 0;
int y = 0;
// move to "bool test()"
std::cout
<< "main, x: " << is_const<decltype(x)>::value << "\n" // true
<< "main, y: " << is_const<decltype(y)>::value << "\n" // false
;
std::cout
<< "test, x: " << test(x) << "\n" // false, I wanted true
<< "test, y: " << test(y) << "\n" // false
;
}
I have unsuccessfully tried various versions similar to:
template<typename T>
bool test(T x)
{
return is_const<???>::value;
}
I want to make sure that I am not missing something and that writing such a testfunction is indeed impossible. (If it was possible, I would also like to know whether a C++03 version was possible.)
Thank you for your consideration
Update
Due to Mankarse I learned that type deduction is different in case of rvalue references:
template<typename T> void t1(T x);
template<typename T> void t2(T& x);
template<typename T> void t3(T&& x);
const int x = 42;
int y = 0;
t1(x); // T = int: t1<int>(int x)
t1(y); // T = int: t1<int>(int x)
t2(x); // T = const int: t2<const int>(const int& x)
t2(y); // T = int: t2<int>(int& x)
t3(x); // T = const int&: t3<const int&>(const int& && x)
t3(y); // T = int&: t3<int&>(int& && x)
In C++11, this can be done with perfect forwarding rvalue references:
In C++03, you can instead use an lvalue reference:
The differences between the two are demonstrated below: