const参数的模板参数推导

时间:2014-12-23 15:03:23

标签: c++ templates

假设我们有

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

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

为什么T被推断为int而不是const int,为什么我可以修改in函数? 在这种情况下扣减如何运作?

Here's a working sample.

2 个答案:

答案 0 :(得分:6)

为什么函数外部的对象const对函数的内部有影响?它正在获取它自己的对象副本,因此它可以自行选择是否将该副本视为const。修改函数内的a不会影响外部对象。这就是因为类型推导而忽略顶级cv限定符的原因。

如果您希望参数为const,则需要提出要求。

答案 1 :(得分:2)

  

为什么T被推断为int而不是const int,为什么我可以修改a   在功能?

因为您通过值传递并按值接收(不是参考)。根据语言语法,这种推论总是优先于非{const const 为了更好地理解,请尝试下面的C ++ 11代码并打印typeid

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

在这种情况下演绎如何运作?

如果您希望a不可修改并尊重传递的对象的const,则在函数中通过引用接收。即。

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

[注意:传递文字不会never work以上签名。]