我有两个版本的相同的静态成员函数:一个采用指向const的指针参数,并采用指向非const的参数.我想避免代码重复.
在阅读了一些堆栈溢出问题(这些都是关于非静态成员函数的)之后我想出了这个:
class C {
private:
static const type* func(const type* x) {
//long code
}
static type* func(type* x) {
return const_cast<type*>(func(static_cast<const type*>(x)));
}
public:
//some code that uses these functions
};
Run Code Online (Sandbox Code Playgroud)
(我知道玩指针通常是一个坏主意,但我正在实现一个数据结构.)
我在libstdc ++中发现了一些如下所示的代码:
注意:这些代码不是成员函数
static type* local_func(type* x)
{
//long code
}
type* func(type* x)
{
return local_func(x);
}
const type* func(const type* x)
{
return local_func(const_cast<type*>(x));
}
Run Code Online (Sandbox Code Playgroud)
在第一种方法中,代码在一个带有指针到const参数的函数中.
在第二种方法中,代码在一个函数中,该函数接受指向非const的参数.
通常应该使用哪种方法?两个都正确吗?