简体   繁体   English

const参数的模板参数推导

[英]template argument deduction for const argument

Suppose we have 假设我们有

template <typename T>
void foo(T a)
{
    a = 10;
}

int main()
{
    const int a = 5;
    foo(a);
}

Why T is deduced as int and not const int, why should I can modify a in function? 为什么T被推断为int而不是const int,为什么我可以修改in函数? How deduction works in this case? 在这种情况下如何扣除?

Here's a working sample. 这是一个工作样本。

Why should the fact that the object outside the function is const matter to the internals of the function? 为什么要一个事实,即在函数外的对象是const事给函数的内部? It is getting it's own copy of the object, so it can choose for itself whether to treat that copy as const or not. 它正在获取它自己的对象副本,因此它可以自己选择是否将该副本视为const Modifying a inside the function will not affect the object outside. 修改a内部功能不会影响以外的对象。 This is the reason that top-level cv-qualifiers are ignored for type deduction. 这就是类型推导忽略顶级cv限定符的原因。

If you want the parameter to be const , you need to ask for it. 如果您希望参数为const ,则需要请求它。

Why T is deduced as int and not const int, why should I can modify a in function? 为什么T被推断为int而不是const int,为什么我可以修改in函数?

Because you are passing by value and receiving by value (not reference). 因为您通过值传递并通过值接收(不是参考)。 According to language grammar such deduction would always result in priority to non-const over const . 根据语言语法,这种推论总是优先于非const而不是const
For better understanding try below C++11 code and print the typeid : 为了更好地理解,请尝试下面的C ++ 11代码并打印typeid

const int a = 5;  // `a` typeid is `const int`
auto b = a;    // `b` typeid is `int`

How deduction works in this case? 在这种情况下如何扣除?

If you want a to be non modifiable and respect the const ness of the object passed then receive by reference in the function. 如果你想要a不可修改的并且尊重传递的对象的const ,那么在函数中通过引用接收。 ie

template<typename T>
void foo (T& a) 
{
  a = 10; // this will result in error if a `const int`
}

[Note: Passing a literal wouldn't never work with above signature.] [注意:传递文字不会对以上签名不起作用 。]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM