使用 Zig 中的 comptime 值格式化字符串

问题描述 投票:0回答:1

我正在尝试创建一个仅接受长度为 4 的内置向量(如

@Vector
)的多态函数。据我了解,向量的长度是 comptime 已知的,我想在编译时错误消息。我知道
@typeName
可用于将类型转换为 comptime 字符串,但是可以用什么来转换 comptime 值呢?

/// x[3] == 1
/// x must be a built-in vector of length 4
pub fn ispoint(x: anytype) bool {
    const T = @TypeOf(v);
    switch (@typeInfo(T)) {
        .Vector => |info| {
            if (info.len != 4) {
                // TODO: report length of provided argument
                @compileError("Not a valid tuple, found Vector of length ???");
            }
            return v[3] == 1;
        },
        else => @compileError("`ispoint` expected a `@Vector(4, T)`, found " ++ @typeName(T)),
    }
}
string formatting metaprogramming zig
1个回答
6
投票

Zig 标准库具有

comptimePrint
,用于在
std.fmt
中进行 comptime 字符串格式化(docs

@compileError(std.fmt.comptimePrint("Not a valid tuple, found a vector of length {}", .{info.len}));
© www.soinside.com 2019 - 2024. All rights reserved.