2017-06-14 83 views
2

如果我理解正确,我们有3例在类型扣除:类型扣除C++标准和自动

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

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

    template< typename T> 
    func1(T & param) 

    func(x) 
    func1(x) 
在两种情况下T被推导为 int

2)PARAM

是指针或引用,在这种情况下,我们忽略参考和指针-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

然而键入模板一样扣除如何与常量性工作的呢? 有

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 = ...

在什么情况下会是常量性忽略,会占上风什么consntess?

+1

'func(5)// param是int &&类型,T是int &&' - 类型错误。 'param'是'int &&',而'T'是'int'。 – StoryTeller

+1

@yeputons:不正确,指针可以有[_qualification conversions_](http://en.cppreference.com/w/cpp/language/implicit_conversion#Qualification_conversions)。这是一个特例。而且由于这个问题明确提到了常量,所以这些资格转换应该是答案的一部分。 – MSalters

+0

你对我没什么意义:你的3种扣除似乎......令人困惑......第一种情况:你说它不是一个参考,那么你在示例中显示一个参考。第二,你说指针,你不会显示指针的例子,你说“我们忽略指针性”,我想不出可能是真实的那个语句的解释。 – bolov

回答

0

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