我的C ++文件中有以下定义:
#define SIZE 32
我想生成以下两行:
typedef uint32_t bui
typedef uint64_t lui
第一行可以通过以下方式生成:
#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
但我不能用
生成第二行typedef NAME(uint,SIZE*2) lui
是否可以在不定义#define DOUBLE_SIZE 64
的情况下执行此操作,仅使用SIZE
宏?
答案 0 :(得分:1)
尽可能(几乎总是)首选模板而不是宏:
#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;
}