【问题标题】:type deduction c++ standard and auto类型推导 c++ 标准和自动
【发布时间】:2017-06-14 13:21:03
【问题描述】:

如果我理解正确的话,我们在类型推导中有 3 种情况:

1) 参数既不是引用也不是指针。

   int x = 5;
   template< typename T>
   func( T param ) 

   template< typename T>
   func1( T & param ) 

   func(x)
   func1(x)

在这两种情况下,T 都被推导出为int

2) 参数是指针或引用,在这种情况下我们忽略引用和指针-ness

   template< typename T>
   func( T & param ) 

   int x = 5;
   const int y =x;
   const int &z =x;

   func(x) // param is type int & and T is type int 
   func(y) // param is type const int & and T is type const int
   func(z) // param is type const int & and T is type const int

3) 参数是“通用引用”。

template< typename T>
func( T && param )

int x = 5;
const int y = x;
const int & z = x;
func(x) // param is type int & and T is type int &
func(y) // param is type const int & T is type const int &
func(z) // param is type const int & and T is type const int &
func(5) // param is type int && and T is type int &&

auto 关键字决定类型,如模板推导,除了

auto x = {1 , 2 , 3} 其中auto x 的类型是initalizer_list

但是,这如何与 constness 一起工作? 有

struct Test{ int x };
Test t;
const Test & t1 = t;
auto t2 = t1; // t2 is type of Test not const Test &

例如如果我们通过了

const int* const x = ...

在什么情况下 constness 会被忽略,什么 constness 会占上风?

【问题讨论】:

  • func(5) // param is type int &amp;&amp; and T is type int &amp;&amp; - 错误。 paramint&amp;&amp;Tint
  • @yeputons:不正确,指针可以有qualification conversions。那是一个特例。而且由于这个问题明确提到了 const-ness,所以这些资格转换应该是答案的一部分。
  • 你对我没有多大意义:你的 3 种类型的推论似乎......令人困惑......第一种情况:你说它不是参考然后你在示例中显示参考。第二个你说指针,你没有显示指针示例,你说“我们忽略指针性”,我想不出对该陈述的解释可能是真的。
  • 试试这个:使用正确的术语编辑您的答案:参数是您声明/定义函数时,参数是您在调用函数时提供给函数的内容。例如:void foo(int a) ; foo(b) 这里a 是参数,b 是参数。并重新审视那个“指针”恶作剧。我看不到在推导上下文中忽略指针类型的场景。

标签: c++ templates type-deduction


【解决方案1】:

auto 使用与template argument deduction 相同的规则:

来自cppreference

一旦确定了初始化器的类型,编译器就会使用从函数调用中推导模板参数的规则来确定将替换关键字auto的类型

所以,按照你的例子:

struct Test{ int x };
Test t;
const Test & t1 = t;
auto t2 = t1; // t2 is Test
const auto t3 = t1; // t3 is const Test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多