AMDiS 2.10
The Adaptive Multi-Dimensional Simulation Toolbox
Literals.hpp
1#pragma once
2
3#include <cassert>
4#include <type_traits>
5
6namespace AMDiS
7{
8 // inspired by Boost.hana
9 // see also: http://blog.mattbierner.com/stupid-template-tricks-stdintegral_constant-user-defined-literal/
10
11 namespace Impl
12 {
13 constexpr unsigned char2digit(const char c)
14 {
15 assert(c >= '0' && c <= '9' && "Unknown digit in integral constant");
16 return unsigned(c) - unsigned('0');
17 }
18
19 template <char... digits>
20 constexpr std::size_t string2num()
21 {
22 const char arr[] = {digits...};
23 assert(arr[0] != '-' && "Negative integral constant");
24
25 std::size_t result = 0;
26 std::size_t power = 1;
27
28 const int N = sizeof...(digits);
29 for (int i = 0; i < N; ++i) {
30 char c = arr[N - 1 - i];
31 result+= char2digit(c) * power;
32 power *= 10u;
33 }
34
35 return result;
36 }
37
38 } // end namespace Impl
39
41 template <char... digits>
42 constexpr auto operator"" _c()
43 {
44 return std::integral_constant<std::size_t,Impl::string2num<digits...>()>{};
45 }
46
47} // end namespace AMDiS