I have a T& which has a const and non-const version of a function. I want to call the const version of the function. I try using std::add_const to turn T& into const T& but it doesn't work. What am I doing wrong and how can I fix it?
Here is a simple example.
void f(int&)
{
std::cout << "int&" << std::endl;
}
void f(const int&)
{
std::cout << "const int&" << std::endl;
}
int main()
{
int a = 0;
int& r = a;
f(static_cast<std::add_const<decltype (r)>::type>(r));
}
Output: int&
Type traits are a very laborious way of approaching this. Simply use template type deduction:
void f(int&)
{
std::cout << "int&" << std::endl;
}
void f(const int&)
{
std::cout << "const int&" << std::endl;
}
template<typename T>
const T& make_const(T& t) { return t; }
int main()
{
int a = 0;
int& r = a;
f(make_const(r));
}
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