Skip to content

Commit a661925

Browse files
Oleksii Dykanfacebook-github-bot
Oleksii Dykan
authored andcommitted
Add a way to get type at index for variant
Summary: This diff adds possibility to extract the type of the nth element of the `CK::Variant`. Unit tests contain the example of extracting the types Reviewed By: Andrey-Mishanin Differential Revision: D24046072 fbshipit-source-id: 5a414929cb543407e5da64b144c90c3413765c6e
1 parent ec29e62 commit a661925

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

ComponentKitTests/CKVariantTests.mm

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,4 +206,15 @@ - (void)test_FunctionPointer
206206
XCTAssertEqual(v, 43);
207207
}
208208

209+
- (void)test_GettingTypeAtIndex
210+
{
211+
Variant<int, std::string>::AlternativeAt<0> intVar = 3;
212+
XCTAssertEqual(intVar, 3);
213+
214+
Variant<int, std::string>::AlternativeAt<1> stringVar = "test";
215+
XCTAssertEqual(stringVar, "test");
216+
217+
// Variant<int, std::string>::AlternativeAt<2> invalidVar; this one fails at compile time
218+
}
219+
209220
@end

RenderCore/Base/CKVariant.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,15 @@ class Variant : private VariantDetail::VariantStorage<Types...>,
492492
// Inherit assignment operators from each of the types in Types
493493
using VariantDetail::VariantChoice<sizeof...(Types), Types...>::operator=;
494494

495+
/**
496+
Provides compile-time indexed access to the types of the variant's alternatives
497+
\code
498+
using T = CK::Variant<bool, short, int>::AlternativeAt<1>; // T == short
499+
\endcode
500+
*/
501+
template <unsigned i>
502+
using AlternativeAt = VariantDetail::NthElement<VariantDetail::Typelist<Types...>, i>;
503+
495504
Variant() = default;
496505

497506
Variant(const Variant& other) {

0 commit comments

Comments
 (0)