我正在使用具有A *寻路算法的库(libtcod)。我的类继承了回调基类,并实现了所需的回调函数。这是我的通用示例:
class MyClass : public ITCODPathCallback
{
...
public: // The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() { // non-const stuff }
};
我发现了一些使用const_cast和static_cast的例子,但它们似乎是另一种方式,使得非const函数能够返回const函数结果。我怎么能在这个例子中做到这一点?
getWalkCost()由我的库定义,我无法更改,但我希望能够在其中执行非常量的东西。
答案 0 :(得分:6)
最好的解决方案取决于你为什么要做非常量的东西。例如,如果您要使用结果缓存来提高性能,则可以使缓存变为可变,因为这样可以保留逻辑常量:
class MyClass : public ITCODPathCallback
{
...
public: // The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() const { // ok to modify cache here }
mutable std::map<int,int> cache;
};
或许您想要记录一些关于调用getWalkCost的次数以及最大x值是多少的统计信息,然后传递对统计信息的引用可能是最好的:
class MyClass : public ITCODPathCallback
{
...
public:
struct WalkStatistics {
int number_of_calls;
int max_x_value;
WalkStatistics() : number_of_calls(0), max_x_value(0) { }
};
MyClass(WalkStatistics &walk_statistics)
: walk_statistics(walk_statistics)
{
}
// The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() const { // ok to modify walk_statistics members here }
WalkStatistics &walk_statistics;
};
答案 1 :(得分:1)
你可以这样破解:
return const_cast<MyClass*>(this)->doSomeMath();
当然,大多数人都认为这不是好设计,但是嘿。如果您愿意,可以改为使用doSomeMath()const,并将其修改的数据成员标记为mutable
。