向前声明 typedef 保护
Forward declare a typedef protection
我正在尝试转发声明一些仅在类中私下使用的变量,以限制使用此变量时必须包含的标头数量。
可悲的是,我要转发声明的类原来是一个 typedef,它是一个我无法编辑的第三方库(为了论证,我们称之为"boost::asio::strand"(
此问题 在 C++ 中转发 typedef 的声明 演示唯一的解决方案是:
- 只需包含标题并接受这是不可能的
- 向前声明什么将被类型定义并添加我自己的类型定义
看看第二个解决方案,有什么方法可以保护自己免受库中的 typedef 更改的影响,以便编译器在删除/重命名类时抱怨 typedef 而不是使用未定义的类型并使其不那么麻烦维护?
如果可能的话,我会尽量不依赖原始类的前向声明。我可能错过了一个案例,但我认为前向声明仅当类型以某种方式出现在方法签名中时,或者如果您的类包含以某种方式指向或引用该类型的成员,可能是间接的,则前向声明仅对纯粹的私人使用有用。
我建议转发声明类的包装器,并且仅在实际的类或typedef已知时才在实现文件中定义它。
假设您的类标头当前如下所示:
// need header because it contains UglyTypeDef:
#include <UglyHeader.h>
class MyClass {
public:
int theMethod(int a);
private:
void uglyMethod(UglyTypeDef &utd);
int someMember;
UglyTypeDef *utdp;
std::vector<UglyTypeDef *> utds;
};
在这个例子中,我们可以使用前向声明,但我们不想依赖 UglyHead 的内部。
我会像这样更改我的类:
class MyClass {
public:
int theMethod(int a);
private:
// move the private method into the implementation file
// hide the ugly typedef
// we safely forward declare our own private wrapper
struct UglyTypeDefWrapper;
int someMember;
UglyTypeDefWrapper *utdp;
std::vector<UglyTypeDefWrapper *> utds;
};
现在,为了使这项工作,cpp 文件中的实现也必须更改:
#include "MyClass.hpp"
#include <UglyHeader.h>
struct MyClass::UglyTypeDefWrapper {
// if possible save another level of indirection
// and store by value, otherwise use a second indirection
// by cleverly wrapping at the right level of abstraction
// this abstraction can be free in many cases
UglyTypeDef td;
};
namespace {
// we completely hide the private method in this file as
// an implementation detail and pass it whatever it needs
// this also helps the compiler to inline it,
// because it knows it cannot be referenced in
// a different compilation unit
// we need to pass all members as needed
void uglyFormerMethod(int &someMember, UglyTypeDef &utd) {
someMember += utd.whatever();
}
}
int MyClass::theMethod(int a) {
utd->td.doWhatever();
uglyFormerMethod(someMember, *utd);
for(auto utdwp: utds) {
utdwp->td.doIt();
}
}
相关文章:
- C++:TypeDef使用元组
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 为什么在保护模式下继承升级不起作用
- 访问被拒绝后,c++中的故障保护代码
- C++:无法访问声明的受保护成员
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 为什么您需要C++头文件的包含保护
- lock_guard是否保护返回值
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 为什么在使用typedef时类推导指南会失败
- 尝试根据类中 typedef 的存在来专门化模板函数
- 继承和友元函数,从基类访问受保护的成员
- 如何重新定义MPI_FLOAT,MPI_DOUBLE以 typedef 的方式
- typedef 枚举和枚举类有什么区别?
- 为什么派生类的好友不能使用受保护的成员?
- C++:为什么无法在派生类中访问受保护的构造函数?
- 在类模板中使用 typedef 时出错
- 模板类中的 typedef 语句
- 向前声明 typedef 保护
- 为什么 typedef 在函数参数中不提供保护