你有没有恨它
class Foobar {
public:
Something& getSomething(int index) {
// big, non-trivial chunk of code...
return something;
}
const Something& getSomething(int index) const {
// big, non-trivial chunk of code...
return something;
}
}
Run Code Online (Sandbox Code Playgroud)
我们无法使用另一个方法实现这两种方法,因为您无法const
从const
版本中调用非版本(编译器错误).演员将被要求const
从非const
一个版本调用该版本.
有没有一个真正优雅的解决方案,如果没有,最接近一个?
我需要从非const对象调用const函数.见例子
struct IProcess {
virtual bool doSomeWork() const = 0L;
};
class Foo : public IProcess {
virtual bool doSomeWork() const {
...
}
};
class Bar
{
public:
const IProcess& getProcess() const {return ...;}
IProcess& getProcess() {return ...;}
void doOtherWork {
getProcess().doSomeWork();
}
};
Run Code Online (Sandbox Code Playgroud)
调用
getProcess().doSomeWork();
Run Code Online (Sandbox Code Playgroud)
总是会打电话给
IProcess& getProcess()
Run Code Online (Sandbox Code Playgroud)
还有另一种方式来打电话
const IProcess& getProcess() const
Run Code Online (Sandbox Code Playgroud)
来自非常数成员函数?我到目前为止使用过
const_cast<const Bar*>(this)->getProcess().doSomeWork();
Run Code Online (Sandbox Code Playgroud)
这样做的技巧,但似乎过于复杂.
编辑:我应该提到代码正在重构,最终只剩下一个函数.
const IProcess& getProcess() const
Run Code Online (Sandbox Code Playgroud)
但是,目前存在副作用,并且const调用可能在某些时候返回不同的IProcess实例.
请继续主题.
什么是implicit_cast?什么时候我应该更喜欢implicit_cast而不是static_cast?
在努力保持正确性的同时,我经常发现自己正在编写这样的代码
class Bar;
class Foo {
public:
const Bar* bar() const { /* code that gets a Bar somewhere */ }
Bar* bar() {
return const_cast< Bar* >(
static_cast< const Foo* >(this)->bar());
}
};
Run Code Online (Sandbox Code Playgroud)
对于很多方法,比如bar()
.编写这些非const方法,手动调用常量方法是乏味的; 此外,我觉得我在重复自己 - 这让我心疼.
我该怎么做才能减轻这个任务?(不允许使用宏和代码生成器.)
编辑:除了litb的解决方案,我也喜欢我自己的解决方案.:)