重铸const函数
Recasting const function
我正在使用具有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
。
相关文章:
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 从函数返回const char*数组
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 在 const 函数中通过引用和指针返回之间的区别
- 使用 std::string () const 函数启动线程或未来
- 在运算符重载定义中使用成员函数(const错误)
- 使用共享指针的函数调用,其对象应为 const
- 将函数参数"const char*"转换为"std::string_view"是
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 使用按引用调用时,不能在没有对象的情况下调用成员函数 const
- 在呼叫运算符函数const中调用运算符时错误
- 我需要用c ++ 98重写c ++ 11代码,c ++ 11正在使用lambda函数[&](const Output & o
- 函数 const 本地对象在C++会发生什么
- int const函数(参数)、int函数(const参数)和int函数(parameters)const之间的区别是什
- const_cast为函数const设置规则并破坏规则
- 构造函数"const variables"设置的用于表示C++数组的边界?
- 将char**传递给C++中的函数(const char**)
- 复制构造函数const char*和Shared_ptr
- 使函数"const"的意图是什么
- c++嵌套映射不匹配成员函数const成员