Domanda

There is a lot of wide string numeric constants defined in one include file in one SDK, which I cannot modify, but which gets often updated and changed. So I cannot declare the numeric define with the numbers because It is completely different each few days and I don't want ('am not allowed) to apply any scripting for updating

If it would be the other way round and the constant would be defined as a number, I can simply make the string by # preprocessor operator.

I don't won't to use atoi and I don't want to make any variables, I just need the constants in numeric form best by preprocessor.

I know that there is no reverse stringizing operator, but isn't there any way how to convert string to token (number) by preprocessor?

È stato utile?

Soluzione

There is no way to "unstringify" a string in the preprocessor. However, you can get, at least, constant expressions out of the string literals using user-defined literals. Below is an example initializing an enum value with the value taken from a string literal to demonstrate that the decoding happens at compile time, although not during preprocessing:

#include <iostream>

constexpr int make_value(int base, wchar_t const* val, std::size_t n)
{
    return n? make_value(base * 10 + val[0] - L'0', val + 1, n -1): base;
}

constexpr int operator"" _decode(wchar_t const* val, std::size_t n)
{
    return make_value(0, val, n);
}

#define VALUE L"123"
#define CONCAT(v,s) v ## s
#define DECODE(d) CONCAT(d,_decode)

int main()
{
    enum { value = DECODE(VALUE) };
    std::cout << "value=" << value << "\n";
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top