从printf格式字符串中提取类型信息
Extracting type info from printf format string
我想从printf格式字符串中提取c++类型信息。例如
Input: "%10u foo %% %+6.3f %ld %s"
Output:
unsigned int
double
long
char*
我已经尝试使用来自printf.h的parse_printf_format(),但是返回的argtypes似乎不包括关于signed/unsigned的信息。
是否有一些方法来获得签名/未签名的信息?
正如我在回答中所说的,parse_printf_format不是为您所需要的而创建的。您可以自己解析它,通过以下算法:
- 因为
%
后面的字符是修饰符或类型(不能两者都是),您首先在字符串 中搜索 - 如果下一个字符是在数组类型('d', 's', 'f', 'g', 'u'等…),那么你得到的类型类(指针,int, unsigned, double等…)。这可能已经足够满足你的需求了。
- 如果没有,则继续查找下一个字符,直到找到一个在修饰符/类型数组中不允许的字符。
- 如果类型的类不足以满足你的需要,你必须回到修饰器来调整最终的类型。
%
字符对于真正的算法,您可以使用许多实现(例如boost),但是由于您不需要验证输入字符串,因此手工验证要简单得多。
伪代码:
const char flags[] = {'-', '+', '0', ' ', '#'};
const char widthPrec[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '*'}; // Last char is an extension
const char modifiers[] = { 'h', 'l', 'L', 'z', 'j', 't' };
const char types[] = { '%', 'd', 'i', 'u', 'f', 'F', 'e', 'E', 'g', 'G', 'x', 'X', 'a', 'A', 'o', 's', 'c', 'p', 'n' }; // Last one is not wanted too
const char validChars[] = { union of all arrays above };
enum Type { None = 0, Int, Unsigned, Float, etc... };
Type typesToType[] = { None, Int, Int, Unsigned, Float, Float, ... etc... }; // Should match the types array above
// Expect a valid format, not validation is done
bool findTypesInFormat(string & format, vector<Type> types)
{
size_t pos = 0;
types.clear();
while (pos < format.length())
{
pos = format.find_first_of('%', pos);
if (pos == format.npos) break;
pos++;
if (format[pos] == '%') continue;
size_t acceptUntilType = format.find_first_not_of(validChars, pos);
if (pos == format.npos) pos = format.length();
pos --;
if (!inArray(types, format[pos])) return false; // Invalid string if the type is not what we support
Type type = typesToType[indexInArray(types, format[pos])];
// We now know the type, we might need to refine it
if (inArray(modifiers, format[pos-1])
{
type = adjustTypeFromModifier(format[pos-1], type);
}
types.push_back(type);
pos++;
}
return true;
}
// inArray, indexInArray and adjustTypeFromModifier are simple functions left to be written.
相关文章:
- C++从通用引用中提取实际类型
- Clang 工具,用于提取给定 lambda 类型的 lambda 主体
- 将不同类型的模板参数包提取到双精度向量中会产生警告
- 在C++如何从数组中提取成员并返回成员类型的数组?
- 从 Any 包中提取和匹配 protobuf 消息类型名的首选方法
- 从具有部分专用化的boost:hana::set中提取类型失败
- 如何提取模板参数中传递的类型
- 从 std::set 中提取仅移动类型
- 需要根据读取的数据类型将ifstream提取到单独的数组中
- 如何定义变体<x,y,z>提取模板参数的子类型
- 从传递给模板函数的内部类实例中提取外部类类型
- 防止为字符串流提取运算符不支持的类型实例化模板类 (>>)
- 从参数包中提取成员类型
- 从函数模板类型中提取返回类型
- 仅从decltype(someFunction)中提取参数类型列表
- 接受lambda作为函数参数并提取返回类型
- 从重载函数中提取返回类型
- 如何从Boost::GIL视图类型中提取通道类型
- 从初始值设定项列表中提取模板类型
- 从转换运算符到函数指针提取返回类型和参数类型