优雅地重用将const添加到类实例化中的代码
Elegantly reuse code adding const to a class instantiation
我需要用两个不同的库编译相同的代码。一个允许对象为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:正如Peter Wood所说,可以将它们实例化为非const。我改了句
您可以使用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
我很确定你是在用预处理器来完成你的目标。
但是,我可能会这样写:
#ifdef OLDLIB
# define LIB_CONST
#else
# define LIB_CONST const
LIB_CONST ClassFoo TheFoo(Bar());
这两种方式都不是很优雅,但这样做至少意味着你只是通过预处理器调整对象属性,而不是整个对象声明。
最简单的解决方案似乎是使用非const对象,并让编译器在新接口需要它的地方自动添加const。
或者你可以在proprocessor块中使用typedef吗?
#ifdef (OLDLIB)
typedef ClassFoo InstantiableFoo;
#else
typedef const ClassFoo InstantiableFoo;
#endif
可以输入pedef
// oldlib.h
typedef ClassFoo Foo;
typedef ClassBar Bar;
// newlib.h
typedef const ClassFoo Foo;
typedef const ClassBar Bar;
// the library's user
#include "oldlib.h" // or include "which_lib.h" that includes
// one of oldlib.h newlib.h
#include "your_library_that_uses_the_typedefs.h"
Foo TheFoo = Bar();
Bar TheBar = FooBar();
你可以参数化库的类和全局函数
// library.h
template <class Foo>
class SomeClass { }
template <class Foo>
Foo makeFoo() { }
// library_user.cpp
#include "library.h"
SomeClass<const ClassFoo> sc;
sc.method();
const ClassFoo f = makeFoo();
你甚至可以在外部库
中隐藏Foo类型// external_library.h
class ExternalLibrary {
typedef const Foo foo_type;
};
ExternalLibrary::foo_type& foo_identity(const ExternalLibrary::foo_type &v) { return v; }
// your_library.h
ExternalLibrary::foo_type makeFoo() { }
foo_identity(f1);
相关文章:
- 为什么我们不在下面给出的代码中使用指针来实例化C++的实体对象?
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 在C++代码中搜索对象的实例化位置
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- 根据运行时参数避免模板实例化的代码重复
- 如何在代码中创建抽象类,让蓝图扩展它,并将该蓝图返回给代码进行实例化?
- 如何在代码中实例化 Vst3 插件?对于 vst3 主机应用
- 生成代码实例化具有不同参数的函数模板
- 如何使用 C++11 unique_ptr实例化我的代码
- 在CNI/C++代码中实例化一个模板类
- 获取在C++中实例化的TCL解释器中执行代码的行号
- 我可以使用decltype()来避免显式模板实例化中的代码重复吗
- 如何在函数调用的一行代码中实例化类
- typedef和显式实例化之间的代码重复
- 用于实例化模板化代码的显式习惯用法 - 不包括其源代码
- 为什么下面的代码会导致模板实例化
- 强制 clang 为类模板实例化的从不引用的静态成员函数发出代码
- C++模板中条件代码实例化的最干净方法
- C++模板函数实例化代码大小
- 编译器:类实例化代码是如何编译的