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的错误消息:
Run Code Online (Sandbox Code Playgroud)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; ^
但是为什么编译器会尝试将const参数绑定到一个带有非 -const参数的函数模板 ?
这个C++模板规则背后的理由是什么?
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)