首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型演绎c++标准和auto

类型演绎c++标准和auto
EN

Stack Overflow用户
提问于 2017-06-14 21:21:03
回答 1查看 347关注 0票数 2

如果我没理解错的话,我们有3个类型推导的案例:

1) param既不是引用也不是指针。

代码语言:javascript
复制
   int x = 5;
   template< typename T>
   func( T param ) 

   template< typename T>
   func1( T & param ) 

   func(x)
   func1(x)

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

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

代码语言:javascript
复制
   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) param是“通用参考”。

代码语言:javascript
复制
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一起工作的?拥有

代码语言:javascript
复制
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= ...

在什么情况下,一致性会被忽略,什么情况下会占上风?

EN

回答 1

Stack Overflow用户

发布于 2018-01-19 17:30:30

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

来自cppreference

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

所以,按照你的例子:

代码语言:javascript
复制
struct Test{ int x };
Test t;
const Test & t1 = t;
auto t2 = t1; // t2 is Test
const auto t3 = t1; // t3 is const Test
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44546064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档