如果我没理解错的话,我们有3个类型推导的案例:
1) param既不是引用也不是指针。
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 int3) param是“通用参考”。
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= ...
在什么情况下,一致性会被忽略,什么情况下会占上风?
发布于 2018-01-19 17:30:30
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 Testhttps://stackoverflow.com/questions/44546064
复制相似问题