在不执行程序的情况下在C ++ 11中检索auto的类型 [英] Retrieving the type of auto in C++11 without executing the program

查看:57
本文介绍了在不执行程序的情况下在C ++ 11中检索auto的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用 auto 推断类型的C ++ 11代码,我必须将其转换为C ++ 98。我将如何转换代码,以实际类型替换所有 auto 实例?

I have some C++11 code using the auto inferred type that I have to convert to C++98. How would I go about converting the code, substituting in the actual type for all instances of auto?

推荐答案

它将是一个PITA,但是您可以声明一个不完整的结构模板,该结构模板接受单个类型参数。

It is going to be a PITA, but you can declare an incomplete struct template accepting a single type parameter.

给出变量 x 的类型,可以将结构体与<$ c $一起使用c> decltype(x),这将导致编译器错误,向您显示推断的类型。

Given the variable x you want to know the type of, you can use the struct with decltype(x) and that will lead to a compiler error that will show you the inferred type.

例如:

template<class Type> struct S;

int main() {
    auto x = ...;
    S<decltype(x)>();
}

实时演示

这将产生以下形式的错误消息:

which will produce an error message in the form:

error: implicit instantiation of undefined template 'S<X>' (clang++)
error: invalid use of incomplete type 'struct S<X>' (g++)

X 是推断的类型。在这种情况下,类型为 int

with X being the inferred type. In this particular case the type is int.

琐事:作者:斯科特·梅耶(Scott Meyer)在NDC 2014的最新视频之一(我不记得是哪一个)中。

Trivia: This has been recommended by Scott Meyer in one of the recent NDC 2014's videos (I don't remember which one).

这篇关于在不执行程序的情况下在C ++ 11中检索auto的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆