Skip to content

whaiman/typecore

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TypeCore

A lightweight, header-only C++23 library for automatic runtime type detection from strings.

Supported types

Type Example input
bool "true", "false"
char "A", "z"
int "-5"
long "-2147483649"
long long "-9999999999999"
unsigned int "42"
unsigned long "4294967296"
unsigned long long "99999999999999999"
float "3.14"
double "3.141592653589793"
std::string "hello" (fallback)

Installation

Just copy include/typecore/typecore.hpp into your project - no build system required.

Usage

#include <typecore/typecore.hpp>
#include <iostream>

int main() {
    auto v = typecore::detect("3.14");

    std::visit([](const auto &val)
               {
        using T = std::decay_t<decltype(val)>;
        std::cout << typecore::type_name<T>() << ": " << val << "\n"; }, v);
    return 0;
    // → float: 3.14
}

Strict mode

By default, unrecognized input falls back to std::string. Pass strict = true to throw instead:

typecore::detect("???", true); // throws std::invalid_argument

Compilation

With g++ / clang++

g++ -std=c++23 -Iinclude main.cpp -o main

With rgcc

Add -Iinclude to your build.json:

{
  "language": "c++",
  "std": "c++23",
  "compiler": "g++",
  "flags": ["-Wall", "-O2", "-Iinclude"],
  "output": "main.exe"
}

Then run:

rgcc compile ./main.cpp

Extending

Adding a new type (example: long double)

1. Add to Value

using Value = std::variant<
    int, double, float, long double, bool, char, std::string,
    long, long long,
    unsigned int, unsigned long, unsigned long long>;

2. Add type_name<T>() specialization

template <>
constexpr const char* type_name<long double>() { return "long double"; }

3. Add try_parse call in detect()

// --- floating point ---
if (auto f  = try_parse<float>(input))       return *f;
if (auto d  = try_parse<double>(input))      return *d;
if (auto ld = try_parse<long double>(input)) return *ld; // ← new

Rules for ordering in detect()

  • bool and char - always before numbers
  • Signed integers: narrow → wide (intlonglong long)
  • Unsigned integers: narrow → wide (unsigned int → ... → unsigned long long)
  • Floating point: narrow → wide (floatdouble)
  • std::string - always last as fallback

All three steps are required for every new type: Value, type_name, try_parse in detect().

License

MIT

About

Header-only C++23 library for automatic runtime type detection from strings

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages