Const参数绑定到C++模板中的非const引用

Mr.*_*C64 2 c++ templates const reference

考虑类似的事情:

template <typename T>
void f(T& x) 
{
    ....       
}
Run Code Online (Sandbox Code Playgroud)

为什么喜欢绑定?const intf(T&)

这在我看来有点违反了const-correctness.实际上,如果f()采用 const T&引用,则很可能f()修改其参数(否则,f()将被定义为void f(const T&)).

在这样的代码中:

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

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

    const int cn = 10;
    f(cn);
}
Run Code Online (Sandbox Code Playgroud)

编译器试图调用f()T = const int,那么当然有由于一个错误消息x = 0;内分配f()的身体.
这是来自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;
       ^
Run Code Online (Sandbox Code Playgroud)

但是为什么编译器会尝试将const参数绑定到一个带有 -const参数的函数模板 ?

这个C++模板规则背后的理由是什么?

Jar*_*d42 8

T绑定到const int.

为避免这种情况,您可以使用SFINAE:

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

删除功能:

template <typename T> void f(T& arg) {}
template <typename T> void f(const T&) = delete;
Run Code Online (Sandbox Code Playgroud)