George Kourtis
George Kourtis

Reputation: 2592

C preprocessor substitution and concatenation

I am trying to define

#define tokenBits 32
typedef inttokenBits_t Token;
typedef int#tokenBits#_t Token;
typedef int##tokenBits##_t Token;
typedef int###tokenBits###_t Token;
const tokenBase=numeric_limits<Token>::min()

How should I define it in order to get

typedef int32_t Token;

Where is exactly written the way of functioning of #define (I found texts both none gives the full vision).

Upvotes: 1

Views: 322

Answers (3)

Jarod42
Jarod42

Reputation: 217225

use template:

template <std::size_t N> struct sized_int;

template<> struct sized_int<32> { using type = int32_t; };
template<> struct sized_int<64> { using type = int64_t; };

#define tokenBits 32

using Token = typename sized_int<tokenBits>::type;

Upvotes: 0

R Sahu
R Sahu

Reputation: 206577

My suggestion:

#define CONCAT(a,b,c) a ## b ## c
#define MYINT_TYPE(tokenBits) CONCAT(int, tokenBits, _t)

typedef MYINT_TYPE(tokenBits) Token;

Upvotes: 3

erenon
erenon

Reputation: 19118

Use a macro:

#define BIT_AWARE_TYPEDEF(bitness, type, result) typedef type##bitness##_t result;

Less configurability:

#define TOKEN(bitness) typedef int##bitness##_t Token;

Upvotes: 1

Related Questions