Constant arguments related to non-constant references in C ++ templates

Consider something like:

template <typename T>
void f(T& x) 
{
    ....       
}

Why is something kind of attached to ? const intf(T&)

This seems like a kind of const-correctness violation. In fact, if it f()accepts a non-const reference T&, then it is very likely that it f()will change its argument (otherwise f()it would be defined as void f(const T&)).

In this code:

template <typename T>
inline void f(T& x) 
{
    x = 0;
}

int main() 
{
    int n = 2;
    f(n);

    const int cn = 10;
    f(cn);
}

the compiler tries to call f()with T = const int, then, of course, an error message appears due to assignment x = 0;inside the body f().
This is the error message from GCC:

test.cpp: In instantiation of 'void f(T&) [with T = const int]':
test.cpp:13:9:   required from here
test.cpp:4:7: error: assignment of read-only reference 'x'
     x = 0;
       ^

But why is the compiler trying to bind the const argument to a function template that takes a non-constant parameter?

++?

+3
3

std::enable_if , . std::is_const, T const.


Re & hellip;

" ++?"

, , , , , : .

+3

T const int.

, SFINAE:

template<typename T>
typename std::enable_if<!std::is_const<T>::value, void>::type
f(T& arg) {}

:

template <typename T> void f(T& arg) {}
template <typename T> void f(const T&) = delete;
+4
const int cn = 10;

This means that 'cn' is const, you cannot change it anyway, anywhere and anytime.

More details:

const int cia = 10;
int ia = 10;

Type cia is different from ia. So T will be const int, not int.

typedef const int      cint;
cint cia = 10;
int ia = 10;

T will be used as cint, not int.

0
source

All Articles