c++ - C++ 中的连接宏

标签 c++ macros concatenation c-preprocessor

我的 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 宏来实现?

最佳答案

尽可能(几乎总是)优先使用模板而不是宏:

#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;
}

关于c++ - C++ 中的连接宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43015156/

相关文章:

c++ - 无法为托管代码运行非托管 cpp 单元测试

c++ - 使用链表的摘要报告代码中的错误

c++ - 所有 constexpr 变量都隐式内联吗?

c - 为什么这个宏被定义为({ 1; })?

clojure - 使用包含类型提示的宏生成Clojure代码

python - python中两个或多个base64字符串的连接

c++ - 打开/写入多个文件

c++ - 创建一个类似 Q_PROPERTY 的宏并提取 __VA_ARGS__

php - 在 Smarty 中连接变量和字符串以包含文件

c - 是否有任何函数可以将字符作为字符串前缀并存储在同一个字符串中?