fn MyType(T: type, comptime tag: [] u8, comptime count: usize) type {
const capitalized = some_module.capitalize(tag);
return struct{
fn name() []const u8 {
return capitalized;
}
array: [count]T,
};
}
for exampleFurthermore, the original argument wasn't about whether something can or can't be done in C++, it was that this one feature in Zig subsumes what would require a multitude of features from C++, such as consteval, templates, SFINAE, type traits, so on so forth...
Instead of having all these disparate features all of which work in subtly different ways, you have one single feature that unifies all of this functionality together.
#include <cstdio>
namespace detail {
template<size_t N>
struct Capitalize {
char data[N];
constexpr Capitalize(const char (&tag)[N]) : data{} {
for (size_t i = 0; i < N; i++)
data[i] = tag[i];
data[0] &= 95;
}
};
}
template<typename T, size_t N, const char (&tag)[N], size_t count>
struct MyType {
static constexpr auto capitalized = detail::Capitalize(tag);
constexpr auto name() const {
return capitalized.data;
}
T array[count];
};
int main() {
static constexpr char hello[] = "hello";
MyType<int, sizeof(hello), hello, 10> value{};
std::puts(value.name());
}
I'd agree that zig's comptime encompasses many of C++'s features, and I appreciate the approach they took to new features by way of builtins (like @typeInfo + @Type for reflection), but this is not a good example.Furthermore, why is type traits among the list of features that you claim is subsumed by comptime? not only is that not the case, but type traits are not so much a feature of C++ as they are of its standard library, implemented using templates (a feature of the language).
Rust on the other hand... that might be ten years.
I still think that language support us important, but unfortunately due to what happened, I suspect that will take a long time. And that’s disappointing.
I agree it'd be nice if it weren't confined to our community, though.
Don't coherence rules prevent it?
error: type capture contains reference to comptime var
I'm not sure how you were suppossed to use it but here's my attempt: fn capitalize(tag: []u8) []u8 {
tag[0] &= 95;
return tag;
}
fn MyType(T: type, comptime tag: []u8, comptime count: usize) type {
const capitalized = capitalize(tag);
return struct {
fn name() []const u8 {
return capitalized;
}
array: [count]T,
};
}
pub fn main() void {
comptime var hello: [5]u8 = undefined;
@memcpy(&hello, "hello");
var v: MyType(i32, &hello, 10) = undefined;
v.name();
}
If you allow `capitalized` to be it's own instance then there's no reason to mutate the comptime parameter in the first place, and it can be replicated in C++17.