【发布时间】:2010-12-31 08:48:37
【问题描述】:
我想知道是否可以将类型确定为 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;
}
对于这个例子,有两个问题:
(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], "int")==0)
{
int t = 2;
cout << t << endl;
}else if (strcmp(argv[1], "float")==0)
{
float t = 2.2;
cout << t << endl;
}
return 0;
}
并可能使用模板函数使各种类型的通用代码可重用。
(b) 或者可以使用抽象类类型和多态性来间接导出定义,但我不确定具体如何。
感谢您的建议!
【问题讨论】: