C++11 auto 和 void* 泛型

C++11 auto and void* generics

基于 ,我可以推断 int age = 45; auto* page = &age; std::cout << *page; 将允许在 c++ 中使用真正的泛型,而 void* 需要了解类型才能转换它并获取值吗?

我正在重新学习c++,我认为auto*会是void*的一个非常合适和理想的替代品。

auto foo = GetFoo(); 并不是要替代 void*autoed 变量有一个非常具体的、编译时确定的类型。 auto 关键字表示编译器 "Please, infer the object type for me"。实际上,您不能只声明一个 auto 变量。你必须给它赋值,这样编译器才能知道它到底是什么类型)

这对于模板化类型特别有用,模板化类型可能具有繁琐、冗长且难看的语法,但绝对不适用于泛型编程。

顺便说一句 auto* 并没有真正添加任何内容 auto。在每种情况下,类型由表达式右侧给出。

auto* foo = nullptr;   // compile error: cannot determine type
void* vFoo = nullptr;  // OK, void* type variable
int bar = 5;           // declares int variable
auto pBar = &bar;      // compile-time determined type: int*
auto* pBar2 = &bar;    // same as pBar
vFoo = &bar;           // OK
double otherBar = 5.0; // declares double variable
pBar = &otherBar;      // compile error: wrong type 

I am studying c++ again and thought auto* would be a very suitable and ideal replacement for void*.

不,那行不通。

int i;
auto* p1 = &i;
double d;
auto* p2 = &d;

p1 = p2; // Won't work.

尽管 p1p2 是使用 auto 关键字声明的,但这些对象的类型是不同的。他们分别是int*double*

如果我们用过

void* p1 = &i;
void* p2 = &d;

以下就可以了

p1 = p2;

核心语言级别不提供对泛型的支持。您必须使用 std::any or boost::any 来获得对泛型的支持。

void*有用的应用它丢弃了所有类型的信息,让你玩记忆。而 auto 在编译时推断类型信息。

例如,您可以有一个向量 void*:

// please don't do that unless you have good reason.
std::vector<void*> vars;

vars.push_back(new int);
vars.push_back(new double);

但这不适用于 auto,因为它必须在编译时推断。即使推断出来,容器也会包含所有相同的类型:

// An old concept syntax, rejected

std::vector<auto*> vars = std::vector<int*>{};

vars.push_back(new int);
vars.push_back(new double); // error! double* is not int*!

auto都是编译时。 void* 删除所有编译时知识。所以 auto 不是 void* 的替代品,而是恰恰相反。