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

I have a T & which has a const and non-const version of a function. I want to call the const version of a function. I am trying to use std :: add_const to include T & in const T & but this will not 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&

+4
source share
6 answers

Typical traits are a very painstaking way to approach this. Just use template type output:

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));
}
+6
source

Links cannot be cv-qualified, therefore std::add_const, applied to the reference type, leaves it unchanged. In this particular case, you should simply do

f(static_cast<const int&>(r));

T :

template<typename T>
struct add_const_to_reference {
    typedef T type;
};

template<typename T>
struct add_const_to_reference<T&> {
    typedef const T& type;
};

template<typename T>
struct add_const_to_reference<T&&> {
    typedef const T&& type;
};
+4

std::add_const , const-, , , .

const:

int main()
{
    int a = 0;
    int& r = a;
    const int &const_r = r;
    f(const_r);
}

:

int main()
{
    int a = 0;
    int& r = a;
    const auto &const_r = r;
    f(const_r);
}
+2

, std::cref:

#include <functional>

int main()
{
    int a = 0;
    int& r = a;
    f(std::cref(r));
}

cref std::reference_wrapper<const int>, const int&.

- reference-to-const-something, , @Brian, decltype -, @BenVoigt, - , cref:

int main()
{
    int a = 0;
    int& r = a;
    using ConstRefT = decltype(std::cref(r))::type &;
}
+2

, , - , .. static_cast<(void(*)(const int&)>(f)(r). , , . f( static_cast<const int&>( r ) ), static_cast .

int main()
{
    int a = 0;
    int& r = a;
    f(static_cast<int const&>(r));
}

If you want to generalize this by creating modifiers for the standard library type, you can do this as follows:

f(static_cast<std::remove_reference<decltype(r)>::type const&>(r));

Since this is pretty ugly, I recommend simply defining a generic const-adder or ad-hoc that declares a link constlocally, and use this as an argument.

A common const-adder might look like this:

template< class Type >
auto const_ref( Type const& r ) -> Type const& { return r; }
+1
source

const_cast- This is what you need. See: http://www.cplusplus.com/doc/tutorial/typecasting/

-1
source

Source: https://habr.com/ru/post/1540914/


All Articles