在C++中是否有可能拥有一个static
和virtual
?的成员函数?显然,没有一种直接的方法(static virtual member();
编译错误),但是至少有一种方法可以达到同样的效果吗?
IE:
struct Object
{
struct TypeInformation;
static virtual const TypeInformation &GetTypeInformation() const;
};
struct SomeObject : public Object
{
static virtual const TypeInformation &GetTypeInformation() const;
};
Run Code Online (Sandbox Code Playgroud)
这是有道理的使用GetTypeInformation()
上的一个实例(都object->GetTypeInformation()
)和一类(SomeObject::GetTypeInformation()
),它可以为模板,比较有用和重要.
我能想到的唯一方法包括编写两个函数/一个函数和一个常量,每个类,或使用宏.
还有其他方法吗?
我的一个朋友问我"如何使用CRTP替换多级继承中的多态".更准确地说,在这种情况下:
struct A {
void bar() {
// do something and then call foo (possibly) in the derived class:
foo();
}
// possibly non pure virtual
virtual void foo() const = 0;
}
struct B : A {
void foo() const override { /* do something */ }
}
struct C : B {
// possibly absent to not override B::foo().
void foo() const final { /* do something else */ }
}
Run Code Online (Sandbox Code Playgroud)
我和我的朋友都知道CRTP不是多态的替代品,但我们对可以使用这两种模式的情况感兴趣.(为了这个问题,我们对每种模式的利弊都不感兴趣.)
之前已经问过这个问题,但事实证明作者想要实现命名参数idiom …
如果我有一个带有2个必需参数和4个可选参数的构造函数,如果我使用默认参数(我不喜欢因为它很差),我怎么能避免编写16个构造函数,甚至编写10个左右我必须编写的构造函数自文档)?有没有使用模板的习语或方法我可以使用它来减少繁琐?(更容易维护?)
我一直在为Windows开发一个GUI库(作为个人辅助项目,没有实用性的愿望).对于我的主窗口类,我已经设置了一个选项类的层次结构(使用命名参数成语),因为一些选项是共享的,而其他选项是特定于特定类型的窗口(如对话框).
命名参数Idiom的工作方式,参数类的函数必须返回它们被调用的对象.问题是,在层次结构中,每个都必须是一个不同的类 - createWindowOpts
标准窗口的createDialogOpts
类,对话框的类等.我通过制作所有选项类模板来解决这个问题.这是一个例子:
template <class T>
class _sharedWindowOpts: public detail::_baseCreateWindowOpts {
public: ///////////////////////////////////////////////////////////////
// No required parameters in this case.
_sharedWindowOpts() { };
typedef T optType;
// Commonly used options
optType& at(int x, int y) { mX=x; mY=y; return static_cast<optType&>(*this); }; // Where to put the upper-left corner of the window; if not specified, the system sets it to a default position
optType& at(int x, int y, int width, int height) { …
Run Code Online (Sandbox Code Playgroud)