不知道C++11类型推理
Have no idea about C++11 type inference
不知道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)
,并对自己说"foo
的T
部分必须是与之匹配的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
如果x
是int
,float
如果x
是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>
当input
是int
的向量时,这里decltype (foo(input[0]))
float
,因为input[0]
是一个int
,并且采用int
的foo
的重载返回float
。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 推理类型如何工作"auto"和按引用调用?
- CAN模板类型推理考虑原始操作类型转换
- 从函数指针对标准 C++98 中的函数类型参数进行静态推理
- 在C++11类型推理过程中,控制优先级的规则是什么
- C++11 类型推理如何在浮点数或双精度数之间做出决定
- 带有函子的自动类型推理不起作用
- C++11 使用 lambda 和 std::function 进行类型推理
- 矩阵积的 Cholesky 的特征和 C++11 类型推理失败
- 使用模板化复合类型推理实现unique_copy
- 不知道C++11类型推理