【发布时间】:2015-04-20 18:27:32
【问题描述】:
我正在开发自己的 WinAPI 包装库,它负责处理与 GUI 相关的所有内容。我在 Android 平台上看到了一些移植的解决方案(视图、测量/布局/绘制通道、从 XML 中“膨胀”UI)。
现在:我不想重复自己并手动添加静态方法,例如 create 和 inflate 到每个 View(Button、GridView、TextView 等)。
基类View 派生自(将 View 作为 T 传递):
template<class T>
class ICreatable : std::enable_shared_from_this<T> {
public:
static std::shared_ptr<T> create() {
return std::shared_ptr<T>(new T()); //assume that T has such constructor
}
static std::shared_ptr<T> inflate(AttributeSet* attrs) {
return std::shared_ptr<T>(new T(attrs)); //assume that T has such constructor
}
std::shared_ptr<T> ptr() {
return enable_shared_from_this::shared_from_this();
}
};
子类派生自 View 和 ICreatable:
class Button : public View, public ICreatable<Button> {
//...
}
现在我必须以某种方式处理歧义 - Button 具有 ICreatable 并且 View 和 Button 都作为 T 传递。我希望 Button 用 ICreatable<Button> 覆盖 ICreatable<View>。
- 这在 C++ 中是否可行?
- 如果没有,是否有其他方法 实现这种“自动静态方法添加”?
- 我应该 回到我手动添加静态的第一个(可怕的)想法 每个 View 的 create() 和 inflate() 方法?
编辑:
经过一番讨论,我提出了一种#define 将这些方法缩短为一行的方法:
#define InsertCreatableMethods(T) \
static std::shared_ptr<T> create() {\
return std::shared_ptr<T>(new T());\
}\
static std::shared_ptr<T> inflate(AttributeSet* attrs) {\
return std::shared_ptr<T>(new T(attrs));\
}
//...
class Button : public View {
//...
public:
InsertCreatableMethods(Button)
//...
}
上面的代码是实现我想要的最好的方式(嗯,我认为是最懒惰的方式)。
【问题讨论】:
-
为什么你希望同一个类既是 ICreatable
又是 ICreatable -
我希望每个 View 类只有一个 ICreatable(具有“最新”类为 T),但由于某些 View 派生自其他 View,ICreatable 也与它们一起派生。
-
不,视图不是抽象的。这里还有更长的“继承链”。例如:ICreatable->View->ViewGroup(+ICreatable)->LinearLayout(+ICreatable)
-
你为什么需要所有
shared_from_this的东西? -
我在某处使用它。最初它位于 View 类中(并且 ptr() 返回 shared_ptr
可以动态转换为派生类...
标签: c++ multiple-inheritance class-template