Last active
May 8, 2024 03:36
-
-
Save faresbakhit/fb8b13d8f73ddd3a635ba038737b717c to your computer and use it in GitHub Desktop.
Demonstrate how a dynamic type system might be implemented
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
// File: dynamic.cc | |
// Purpose: Demonstrate how a dynamic type system might be implemented | |
// Author: Fares A. Bakhit | |
// Date: May 8th, 2024 | |
// License: Zero Clause BSD (https://spdx.org/licenses/0BSD.html) | |
#include <cstdint> | |
#include <iostream> | |
using namespace std; | |
// A dynamically-typed variable | |
struct var { | |
enum class type { | |
integer, | |
character, | |
}; | |
var(const int32_t& val) | |
: m_ty(type::integer) | |
{ | |
m_val = malloc(sizeof(int32_t)); | |
*(int32_t*)m_val = val; | |
} | |
void operator=(const int32_t& val) | |
{ | |
if (m_ty == type::integer) { | |
*(int32_t*)m_val = val; | |
return; | |
} | |
m_ty = type::integer; | |
free(m_val); | |
m_val = malloc(sizeof(int32_t)); | |
*(int32_t*)m_val = val; | |
} | |
var(const char& val) | |
: m_ty(type::character) | |
{ | |
m_val = malloc(sizeof(char)); | |
*(int32_t*)m_val = val; | |
} | |
void operator=(const char& val) | |
{ | |
if (m_ty == type::character) { | |
*(char*)m_val = val; | |
return; | |
} | |
m_ty = type::character; | |
free(m_val); | |
m_val = malloc(sizeof(char)); | |
*(char*)m_val = val; | |
} | |
~var() | |
{ | |
free(m_val); | |
} | |
void operator+=(int32_t val) | |
{ | |
switch (m_ty) { | |
case type::integer: | |
*(int*)(m_val) += val; | |
break; | |
default: | |
cerr << "error: invalid type\n"; | |
exit(1); | |
} | |
} | |
type m_ty; | |
void* m_val = nullptr; | |
}; | |
ostream& operator<<(ostream& os, const var& v) | |
{ | |
switch (v.m_ty) { | |
case var::type::integer: | |
os << *(int32_t*)(v.m_val); | |
break; | |
case var::type::character: | |
os << *(char*)(v.m_val); | |
break; | |
} | |
return os; | |
} | |
int main() | |
{ | |
// a character... | |
var mypain = 'F'; | |
//mypain += 32; // this would error at runtime | |
cout << "mypain=" << mypain << '\n'; | |
// is now an integer! | |
mypain = 3; | |
mypain += 2; | |
cout << "mypain=" << mypain << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment