我需要用两个不同的库编译相同的代码。一个允许对象是 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/