[英]Const arguments binding to non-const references in C++ templates
Consider something like: 考虑类似的事情:
template <typename T>
void f(T& x)
{
....
}
Why does something like const
int
binds to f(T&)
? 为什么像
const
int
这样的东西会绑定到f(T&)
?
This seems to me kind of a violation of const-correctness . 这在我看来有点违反了const-correctness 。 In fact, if
f()
takes a non -const T&
reference, then it's very likely that f()
will modify its argument (else, f()
would have been defined as void f(const T&)
). 实际上,如果
f()
采用非反对T&
reference,那么f()
很可能会修改它的参数(否则, f()
将被定义为void f(const T&)
)。
In code like this: 在这样的代码中:
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 there is an error message because of the x = 0;
编译器尝试用
T = const int
调用f()
,当然因为x = 0;
而存在错误消息x = 0;
assignment inside f()
's body. f()
内部的赋值。
This is the error message from GCC: 这是来自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 does the compiler try to bind a const argument with a function template which takes a non -const parameter? 但是为什么编译器会尝试将const参数绑定到一个带有非 -const参数的函数模板?
What's the rationale behind this C++ template rule? 这个C ++模板规则背后的理由是什么?
T
binds to const int
. T
绑定到const int
。
To avoid that, you may use SFINAE: 为避免这种情况,您可以使用SFINAE:
template<typename T>
typename std::enable_if<!std::is_const<T>::value, void>::type
f(T& arg) {}
or deleted function: 或删除功能:
template <typename T> void f(T& arg) {}
template <typename T> void f(const T&) = delete;
You can use std::enable_if
plus eg std::is_const
to avoid that T
binds to a const
type. 您可以使用
std::enable_if
plus例如std::is_const
来避免T
绑定到const
类型。
Re … 回覆 …
“What's the rationale behind this C++ template rule?”
“这个C ++模板规则背后的基本原理是什么?”
it can possibly be found in Bjarne's design-and-evolution book, but about the most common rationale is that the rules have been chosen for simplicity and uniformity, and so it appears to be also here: treating some types in special ways would introduce needless complexity. 它可以在Bjarne的设计和进化书中找到,但关于最常见的理由是,规则是为了简单和统一而选择的,因此它似乎也在这里:以特殊方式处理某些类型会引入不必要的复杂。
const int cn = 10;
That means 'cn' is const, you can't change it in anyway, anywhere and anytime. 这意味着'cn'是const,无论如何,无论何时何地都无法改变它。
More: 更多:
const int cia = 10;
int ia = 10;
The type of cia is different with ia. cia的类型与ia不同。 So T will be const int, not int.
所以T将是const int,而不是int。
typedef const int cint;
cint cia = 10;
int ia = 10;
T will be used as cint, not int. T将用作cint,而不是int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.