不知道C ++ 11类型推断

时间:2011-08-20 06:51:37

标签: c++ c++11 type-inference

不知道C ++ 11类型推断

众所周知,C ++ 11中至少有3种类型的推论:

  • 模板演绎
  • 自动
  • decltype

但我不能为他们建立一个概念模型。这让我感到困惑 这导致我不知道在微妙的情况下什么是正确的。

事实上,我甚至不知道我的问题是什么。 但是,我试试:

我想知道cv,&和&&限定词会影响类型推断 我想知道三种类型推断之间的区别。

///The following extract from 14.8.2.1 in n3242
template <class T> int f(T&&);
template <class T> int g(const T&&);
int i;
int n1 = f(i); // calls f<int&>(int&)
int n2 = f(0); // calls f<int>(int&&)
int n3 = g(i); // error: would call g<int>(const int&&), which
// would bind an rvalue reference to an lvalue

///The following extract from 8.3.2 in n3242
int i;
typedef int& LRI;
typedef int&& RRI;
LRI& r1 = i; // r1 has the type int&
const LRI& r2 = i; // r2 has the type int&
const LRI&& r3 = i; // r3 has the type int&
RRI& r4 = i; // r4 has the type int&
/*The following statement encounter compilation error in gcc 4.6:error message:
invalid initialization of reference of type int&& from expression of type int*/
RRI&& r5 = i; // r5 has the type int&&
decltype(r2)& r6 = i; // r6 has the type int&
decltype(r2)&& r7 = i; // r7 has the type int&

///The following is from some blog
int i;
decltype( i ) ==> int
decltype( (i) ) ==> int &

1 个答案:

答案 0 :(得分:1)

模板推导在C ++ 03中

template <typename T> void foo(T) {}
int i;
float f;
foo (i); // deduces foo<int>
foo (f); // deduces foo<float>

此处编译器会看到foo(i)并对自己说“T的{​​{1}}部分必须是foo才能匹配”。

int非常简单。

auto

编译器看到int foo (); float bar (); auto i = foo (); // i is an int auto f = bar (); // f is a float 并且自己说“好的右手边会产生auto i =,所以int必须是其中之一”。

i更多涉及,一种元自动。如果decltypedecltype(x),则int相当于x,如果intfloatx等等。{是你可以在模板表达式中使用它。

float

int foo (float); float foo (int); template <typename T> void convert (std :: vector <T> input) { std :: vector <decltype (foo(input[0]))> output; output .push_back (foo (input [0])); // yeah, ok, not safe, meh } convert (std :: vector <int> ()); // Will create an output of type std::vector<float> convert (std :: vector <float> ()); // Will create an output of type std::vector<int> decltype (foo(input[0]))的向量时,float inputint,因为input[0]int且{{1}超载需要foo才能返回int

相关问题