Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use std::add_const to turn T& into const T&

Tags:

c++

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&

like image 977
Neil Kirk Avatar asked Dec 09 '22 07:12

Neil Kirk


1 Answers

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));
}
like image 100
Ben Voigt Avatar answered Dec 24 '22 17:12

Ben Voigt