c++ - 优雅地重用将 const 添加到类实例化的代码

标签 c++ constants c-preprocessor

我需要用两个不同的库编译相同的代码。一个允许对象是 const,另一个则不允许。现在实现的解决方案如下所示:

#ifdef (OLDLIB)
    ClassFoo TheFoo = Bar();
#else
    const ClassFoo TheFoo = Bar();
#endif

这在不同的类中使用了很多次并且妨碍了可读性。我想在其他地方做出区分。

我猜有人会说:

#ifdef (OLDLIB)
#define CLASS_FOO ClassFoo
#define CLASS_BAR ClassBar
#else
#define CLASS_FOO const ClassFoo
#define CLASS_BAR const ClassBar
#endif

CLASS_FOO TheFoo = Bar();
CLASS_BAR TheBar = FooBar();

但我不喜欢预处理器的东西。是否有一种很好的 C++ 方式来执行上述操作?谢谢。

更新 1: 正如彼得伍德所说,可以将它们实例化为非常量。我改了个句子。

最佳答案

您可以使用 std::conditional根据编译时变量在两种类型之间进行选择:

#ifdef OLDLIB
constexpr bool OLD = true;
#else
constexpr bool OLD = false;
#endif

std::conditional<OLD, ClassFoo, const ClassFoo>::type theFoo;
                 ~~~  ~~~~~~~~  ~~~~~~~~~~~~~~
                        true        false

自 C++11 起

关于c++ - 优雅地重用将 const 添加到类实例化的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16794425/

相关文章:

c++ - 如果普通默认构造函数不执行任何操作,为什么我们不能使用 malloc 创建普通可构造对象?

c++ - 我应该声明所有不抛出 noexcept 的成员/函数吗?

c++ - 嵌套的 boost (预处理器)序列

c++ - write 返回较小尺寸时该怎么办?

c++ - 从 QTableView 中检索特定列的内容

c++ - 了解 C++ 中对迭代器的常量引用和非常量引用。为什么我不能在打印函数中使用对迭代器的非常量引用?

c++ - 将 const 传递给具有非常量参数的函数

c# - 以编程方式检查构建配置

c++ - 我如何编写一个类似于 __FILE__ 的 cpp __DIR__ 宏

c++ - icc : can the compiler invent writes where none existed in the abstract machine?崩溃