Commit 6643b805 authored by Kenton Varda's avatar Kenton Varda

Add kj::arr() for specifying arrays easily. Requries C++17.

std::initializer_list is problematic because it insists that its elements be const, meaning among other things that you can't move from them. So, an std::initializer_list<kj::String> is often useless. With kj::arr you can do like:

    kj::Array<String> = kj::arr(kj::mv(string1), kj::mv(string2));

This requires C++17 due to the fold expression. This could maybe be worked around using some ugly recursion but I'm writing C++17 these days so meh.
parent ee380345
...@@ -378,5 +378,12 @@ TEST(Array, ReleaseAsBytesOrChars) { ...@@ -378,5 +378,12 @@ TEST(Array, ReleaseAsBytesOrChars) {
} }
} }
#if __cplusplus > 201402L
KJ_TEST("kj::arr()") {
kj::Array<kj::String> array = kj::arr(kj::str("foo"), kj::str(123));
KJ_EXPECT(array == kj::ArrayPtr<const kj::StringPtr>({"foo", "123"}));
}
#endif
} // namespace } // namespace
} // namespace kj } // namespace kj
...@@ -822,6 +822,15 @@ inline Array<T> heapArray(std::initializer_list<T> init) { ...@@ -822,6 +822,15 @@ inline Array<T> heapArray(std::initializer_list<T> init) {
return heapArray<T>(init.begin(), init.end()); return heapArray<T>(init.begin(), init.end());
} }
#if __cplusplus > 201402L
template <typename T, typename... Params>
inline Array<Decay<T>> arr(T&& param1, Params&&... params) {
ArrayBuilder<Decay<T>> builder = heapArrayBuilder<Decay<T>>(sizeof...(params) + 1);
(builder.add(kj::fwd<T>(param1)), ... , builder.add(kj::fwd<Params>(params)));
return builder.finish();
}
#endif
} // namespace kj } // namespace kj
#endif // KJ_ARRAY_H_ #endif // KJ_ARRAY_H_
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment