BioCMAMC-ST
env_var.hpp
1#ifndef __BIOMC_COMMON_ENV_VAR_HPP__
2#define __BIOMC_COMMON_ENV_VAR_HPP__
3#include <cstdio>
4#include <cstdlib>
5#include <optional>
6
7#include <sstream>
8#include <string>
9#include <string_view>
10
11#ifdef _WIN32
12# include <iostream>
13#endif
14
15namespace Common
16{
21 template <typename T>
22 std::optional<T>
23 read_env(std::string_view varname)
24 {
25 const char* env_var = std::getenv(varname.data());
26 std::optional<T> ret = std::nullopt;
27 if (env_var != nullptr)
28 {
29 std::istringstream stream(env_var);
30 T value;
31 stream >> value;
32 if (stream)
33 {
34 std::printf(
35 "[Config] Env value load: %s %s\r\n", varname.data(), env_var);
36 std::fflush(stdout);
37
38 ret = value;
39 }
40 }
41 return ret;
42 }
43
48 template <typename T>
49 T
50 read_env_or(std::string_view varname, T vdefault)
51 {
52 return read_env<T>(varname).value_or(vdefault);
53 }
54
59 template <> bool read_env_or(std::string_view varname, bool vdefault);
60
65 template <typename T>
66 bool
67 set_local_env(std::string_view varname, T val)
68 {
69#ifdef _WIN32
70 // Windows-specific handling (not implemented)
71 std::cerr << "Not implemented for Win32" << std::endl;
72 return false;
73#else
74 std::ostringstream oss;
75 oss << val;
76 std::string str_value = oss.str();
77
78 return setenv(varname.data(), str_value.c_str(), 1) == 0;
79#endif
80 }
81
82 template <>
83 bool set_local_env<std::string>(std::string_view varname, std::string val);
84
85 template <> bool set_local_env<bool>(std::string_view varname, bool val);
86
87} // namespace Common
88
89#endif
Definition config_loader.hpp:8
bool set_local_env< bool >(std::string_view varname, bool val)
Definition common.cpp:69
bool set_local_env(std::string_view varname, T val)
Wrapper arround set_env.
Definition env_var.hpp:67
bool set_local_env< std::string >(std::string_view varname, std::string val)
Definition common.cpp:57
T read_env_or(std::string_view varname, T vdefault)
Wrapper arround get_env to get envariable with fallback to default.
Definition env_var.hpp:50
std::optional< T > read_env(std::string_view varname)
Wrapper arround get_env to get optional envariable.
Definition env_var.hpp:23