-
-
Save advaitraut/0ebced55968538e5bde6be4273532aee to your computer and use it in GitHub Desktop.
Example Either type in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| template <class T1, class T2> | |
| class Either | |
| { | |
| bool isLeft; | |
| union | |
| { | |
| T1 left; | |
| T2 right; | |
| }; | |
| template<class T1_, class T2_> friend Either<T1_, T2_> Left(T1_ x); | |
| template<class T1_, class T2_> friend Either<T1_, T2_> Right(T1_ x); | |
| public: | |
| bool matchLeft(T1& x) | |
| { | |
| if (isLeft) | |
| x = left; | |
| return isLeft; | |
| } | |
| bool matchRight(T2& x) | |
| { | |
| if (!isLeft) | |
| x = right; | |
| return !isLeft; | |
| } | |
| }; | |
| template <class T1, class T2> | |
| Either<T1, T2> Left(T1 x) | |
| { | |
| Either<T1, T2> e; | |
| e.isLeft = true; | |
| e.left = x; | |
| return e; | |
| } | |
| template <class T1, class T2> | |
| Either<T1, T2> Right(T2 x) | |
| { | |
| Either<T1, T2> e; | |
| e.isLeft = false; | |
| e.right = x; | |
| return e; | |
| } | |
| int main(int argc, char* argv[]) | |
| { | |
| Either<int, float> x = Left<int, float>(5); | |
| int c; | |
| if (x.matchLeft(c)) | |
| printf("the number is %i", c); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment