Reputation: 442
I have the following definition in my C++ file:
#define SIZE 32
And I want to generate following two lines:
typedef uint32_t bui
typedef uint64_t lui
The first line can be generated by:
#define PASTER(x,y) x ## y ## _t
#define EVALUATOR(x,y) PASTER(x,y)
#define NAME(fun, size) EVALUATOR(fun, size)
typedef NAME(uint,SIZE) bui
But I cant't generate the second line with
typedef NAME(uint,SIZE*2) lui
Is it possible to do it without defining #define DOUBLE_SIZE 64
, using only SIZE
macro?
Upvotes: 0
Views: 169
Reputation: 69922
Prefer templates over macros where possible (almost always):
#include <cstdlib>
#include <cstdint>
struct Signed {};
struct Unsigned{};
namespace detail {
template<class SignedNess, std::size_t Bits> struct make_int ;
template<> struct make_int<Signed, 64> { using type = std::int64_t; };
template<> struct make_int<Signed, 32> { using type = std::int32_t; };
template<> struct make_int<Signed, 16> { using type = std::int16_t; };
template<> struct make_int<Signed, 8> { using type = std::int8_t; };
template<> struct make_int<Unsigned, 64> { using type = std::uint64_t; };
template<> struct make_int<Unsigned, 32> { using type = std::uint32_t; };
template<> struct make_int<Unsigned, 16> { using type = std::uint16_t; };
template<> struct make_int<Unsigned, 8> { using type = std::uint8_t; };
}
template<class Signedness, std::size_t Bits> using make_int = typename detail::make_int<Signedness, Bits>::type;
int main()
{
make_int<Signed, 16> x = 5;
}
Upvotes: 1