PLaSK library

Loading...
Searching...
No Matches
lexical_cast.hpp
Go to the documentation of this file.
1/*
2 * This file is part of PLaSK (https://plask.app) by Photonics Group at TUL
3 * Copyright (c) 2022 Lodz University of Technology
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14#ifndef PLASK__UTILS_LEXICAL_CAST_H
15#define PLASK__UTILS_LEXICAL_CAST_H
16
21#include <complex>
22
23#include <boost/lexical_cast.hpp>
24#include <boost/algorithm/string/trim.hpp>
25
26 namespace boost {
27
28 template <>
29 inline std::complex<double> lexical_cast(const std::string &arg)
30{
31 std::string src = boost::algorithm::trim_right_copy(arg);
32
33 size_t n = src.length(), i;
34 bool negim = false;
35
36 for (i = 0; i < n; ++i) {
37 if (src[i] == 'e' || src[i] == 'E') {
38 i++; continue;
39 }
40 if (src[i] == '+')
41 break;
42 if (src[i] == '-') {
43 negim = true; break;
44 }
45 }
46
47 std::complex<double> result(0., 0.);
48 try {
49 result.real(boost::lexical_cast<double>(src.substr(0, i)));
50 if (i < n) {
51 if (i > n-3 || (src[n-1] != 'j' && src[n-1] != 'J'))
52 boost::throw_exception(boost::bad_lexical_cast(typeid(std::string), typeid(std::complex<double>)));
53 double im = boost::lexical_cast<double>(src.substr(i+1, n-i-2));
54 if (negim) im = -im;
55 result.imag(im);
56 }
57 } catch (...) {
58 boost::throw_exception(boost::bad_lexical_cast(typeid(std::string), typeid(std::complex<double>)));
59 }
60
61 return result;
62}
63
64
65}
66
67#endif // PLASK__UTILS_LEXICAL_CAST_H