我想知道是否可以将类型确定为C++中的运行时信息.
(1)虽然我的问题很笼统,但为简单起见,我将从一个简单的例子开始:
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char * argv[])
{
if (strcmp(argv[1], "int")==0)
{
int t = 2;
}else if (strcmp(argv[1], "float")==0)
{
float t = 2.2;
}
cout << t << endl; // error: ‘t’ was not declared in this scope
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于此示例,有两个问题:
(a)"argv [1] to t"是错误的,但C字符串argv [1]中的类型信息是否可以转换为实际的类型关键字?所以我们不需要通过if-else子句和strcmp检查每种类型.
(b)如何在if子句的局部范围内定义的变量t仍在外部有效.即如何将局部变量"导出"到其范围之外?
(2)一般来说,不是特定于上面的简单示例,运行时确定类型的常用方法是什么?在我看来,可能有一些方法:
(a)可以将类型定义的变量的处理放在同一范围内定义.例如
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char * argv[])
{
if (strcmp(argv[1], …Run Code Online (Sandbox Code Playgroud)