不知道C++11类型推理

Have no idea about C++11 type inference

本文关键字:推理 类型 C++11 不知道      更新时间:2023-10-16

不知道C++11类型推理

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

  • 模板推断
  • 自动
  • 德克洛类型

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

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

我想知道 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 &

模板推导在 C++03

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

在这里,编译器看到了foo(i),并对自己说"fooT部分必须是与之匹配的int"。

auto很简单。

int foo ();
float bar ();
auto i = foo (); // i is an int
auto f = bar (); // f is a float

编译器看到auto i =并对自己说"好吧,右侧产生一个int所以i必须是其中之一"。

decltype涉及更多,一种元自动。 decltype(x)等价于int如果xintfloat如果xfloat,等等。优点是您可以在模板表达式中使用它。

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>

inputint的向量时,这里decltype (foo(input[0])) float,因为input[0]是一个int,并且采用intfoo的重载返回float