考虑这样的事情:
template <typename T>
void f(T& x)
{
....
}
为什么 const
int
绑定(bind)到 f(T&)
?
在我看来,这有点违反const-correctness。事实上,如果 f()
接受一个 non-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);
}
编译器尝试用 T = const int
调用 f()
,当然会因为 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; ^
但为什么编译器会尝试将 const 参数与采用非-const 参数的函数模板绑定(bind)?
此 C++ 模板规则背后的基本原理是什么?
最佳答案
T
绑定(bind)到 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;
关于c++ - 绑定(bind)到 C++ 模板中非常量引用的常量参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21573541/