Asm*_*iel 5 c++ setter inheritance parent-child mutators
说实话,我真的不知道,怎么问这个问题,所以请不要生气:)
无论如何,我想让我的类中的mutators(setter)返回this以允许类似jQuery,a.name("something").address("somethingelse");
我有一个父类(Entity)和几个子类(Client, Agent etc.).大多数事物的变换器都是从Entity类继承的(比如名称或地址),但它们返回一个Entity对象,所以我不能在它们上面调用Client mutators.
换一种说法:
// name mutator
Entity& Entity::name( const string& name ) {
// [...] checks
_name = name;
return *this;
}
// budgetRange mutator
Client& Client::budgetRange( const long int& range ) {
// [...] checks
_budgetRange = range;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
然后我打电话给它:
Client a; a.name("Dorota Adamczyk").budgetRange(50);
Run Code Online (Sandbox Code Playgroud)
编译器(逻辑上)说,Entity对象没有budgetRange成员(因为name返回一个Entity,而不是Client).
我现在的问题是:我怎么能实现这样的东西?我考虑过重载子类中的所有实体函数,但这不会很好,并且会违背继承的想法:)
提前感谢您的想法:D
您应该使用CRTP.
template<class Derived>
class Entity
{
Derived* This() { return static_cast<Derived*>(this); }
public:
Derived& name(const string& name)
{
...
return *This();
}
};
class Client : public Entity<Client>
{
public:
Client& budgetRange(const long& range)
{
...
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
如果要使用虚函数,还可以添加抽象基类,如下所示:
class AbstractEntity
{
public:
virtual void foo() = 0;
virtual ~AbstractEntity();
};
template<class Derived>
class Entity : AbstractEntity
{...};
Run Code Online (Sandbox Code Playgroud)