为什么不将模板类型参数推断为“ const”? [英] Why aren't template type parameters inferred as 'const'?
问题描述
可能重复:
从右值参数推导const的引用
如果我有
template<class T>
void foo(T &) { }
我称之为 foo((const int)5)
,鉴于该参数是 const int
,为什么编译器不自动推断 T
是 const int
?
and I call it as foo((const int)5)
, given that the argument is a const int
, why doesn't the compiler automatically infer T
to be const int
?
推荐答案
如果给定const类型,则可以。但是,具有
非类类型的Rvalues(在C ++ 11中为prvalues)从不具有cv限定符,即使您试图说出
也是如此:表达式(( const int)5)
的类型为 int
。这里的理由
是cv限定仅适用于对象,而
非类类型的临时对象不是对象,而是纯值; cb资格不能申请
,因为没有 const
或 volatile
。
It does, if it's given a const type. Rvalues (prvalues in C++11) with
non-class types, however, are never cv-qualified, even if you try to say
they are: the expression ((const int)5)
has type int
. The reasoning
here is that cv-qualifications only apply to objects, and temporaries of
non-class types aren't objects, but pure values; cv-qualifications can't
apply, because there's nothing to be const
or volatile
.
如果您这样写:
int const i = 42;
foo( i );
,您的模板将使用 T = int const $ c $实例化c>。 (在您
编写代码时,不应编译该代码,因为推导的类型
是 int
,因此该函数使用的是 int&
,不能将
初始化为右值。)
, your template will instantiate with T = int const
. (As you
wrote it, the code shouldn't compile, because the deduced type
is int
, so the function takes an int&
, which can't be
initialized with an rvalue.)
这篇关于为什么不将模板类型参数推断为“ const”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!