2

Motivation:

Here is the implementation of converting base-n to decimal:

template<int from, char... Chs>
    constexpr int
    toDec()
    {
        int ret{};

        return (
            (ret *= from, ret += Chs > '9' ? Chs - 'A' + 10 : Chs - '0'), ...);
    }
    inline namespace literals
    {
        template<char... Chs>
        constexpr int operator"" _B()
        {
            return toDec<2, Chs...>();
        }
        template<char... Chs>
        constexpr int operator"" _O()
        {
            return toDec<8, Chs...>();
        }
    } // namespace literals

It works fine with base-2 and base-8:

static_assert(111_B == 7);
static_assert(011_B == 3);
static_assert(052 == 52_O);
static_assert(073227 == 73227_O);

But for base-16, because we have non-number char, so numbers like E7_X won't work(error: use of undeclared identifier 'E7_X'), so I use user-defined-string-literal:

constexpr int operator""_X(const char* str, unsigned long)
{
     // do something to unpack str into <char...>, so I can reuse toDec;
}
......

static_assert(0XE7 == "E7"_X);

For dry, I hope to reuse toDec, so I need to unpack str into <char...>, do you have any idea? (If you have any elegant solution for the base-16 case, please tell me, I would very appreciate it!)

and with C++14, binary literals are also standard

Yes, I'm aware of it. Here is just a practice and for some reasons, I hope get base-11/12/13/14... convertion

Chen Li
  • 4,824
  • 3
  • 28
  • 55
  • The `str` parameter isn't (and cannot be) a constant expression, so I'm pretty sure you cannot use it to build a template parameter. I have to ask though, what is the point of `toDec`? It's not like `0x52` and `52_X`would have different values anyway... and with C++14, binary literals are also standard. – Nelfeal Dec 15 '18 at 07:16
  • @Nelfeal Sorry, it's my bad, please give me some time to re-organize the question – Chen Li Dec 15 '18 at 07:30
  • @Nelfeal added and removed some contexts – Chen Li Dec 15 '18 at 07:46
  • 1
    It would make a lot more sense to reuse the other way around. – T.C. Dec 15 '18 at 07:48
  • @T.C. Ok, now that str cannot be unpacked here(just not sure before), it do make a lot more sense to reuse other workaround. – Chen Li Dec 15 '18 at 07:51

0 Answers0