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