【问题标题】:Macro to define a type定义类型的宏
【发布时间】:2015-12-17 03:52:30
【问题描述】:

在 C++ 中有没有一种方法可以根据预处理器标志定义类型?我有两个版本的库,一个是原生的,一个是在 thirft 之上构建的。

两个版本具有完全相同的函数签名,除了返回和参数类型。 native 版本传递对象的指针,thirft 版本使用 i64 表示指针。

我想知道是否有一种方法可以构建一个可以使用任何基于编译标志的库的项目。比如:

//native
AType* obj = fun(AnotherType* another_obj)

//thirft
i64 obj = fun(i64 another_obj)

我想知道是否有这样的构造:

if native
    X is Atype*
    Y is AnotherType*
else
    X is i64
    Y is i64
end

//native
X obj = fun(Y another_obj)

//thirft
X obj = fun(Y another_obj)

【问题讨论】:

    标签: c++ c++11 build


    【解决方案1】:

    如果两个版本都能够使用相同的已知数据进行编译(因此您实际上并没有在不使用它的版本中定义AnotherType,而只是具有不同的函数签名)那么您可以使用std::conditional

    using ActualType = std::conditional<IS_NATIVE, i64, AnotherType>::type;
    

    否则你必须坚持使用复古的#if #else #endif 宏。

    【讨论】:

      【解决方案2】:

      你想要这样的东西:

      #ifdef native
          typedef Atype* X
          typedef AnotherType* Y
      #else
          typedef i64 X
          typedef i64 Y
      #endif
      

      如果始终设置native(设置为非零或零值),您可以改用#if native

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-07
        • 1970-01-01
        • 2015-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多