重铸const函数

Recasting const function

本文关键字:函数 const 重铸      更新时间:2023-10-16

我正在使用具有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()是由我的库定义的,我不能更改,但我希望能够在其中做非const的事情。

最佳解决方案取决于您为什么要使用非const内容。例如,如果您希望使用结果缓存来提高性能,那么您可以将缓存设置为可变的,因为这样可以保留逻辑一致性:

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;
};

你可以这样做:

  return const_cast<MyClass*>(this)->doSomeMath();
当然这不会被大多数人认为是好的设计,但是嘿。如果您愿意,您可以将doSomeMath()改为const,并将其修改的数据成员标记为mutable