相同函数的C const/non-const版本

Tho*_*ing 2 c const

假设在CI中具有这些功能

type* func (type*);
const type* func_const (const type*);
Run Code Online (Sandbox Code Playgroud)

这样它们都具有完全相同的内部逻辑.

有没有办法可以将两者合并为一个函数,如果给定一个const类型,它返回一个const类型; 如果给定一个非const类型,它返回一个非const类型?如果没有,处理这个问题的好方法是什么?也许通过显式铸造来定义另一个?

Jim*_*uck 10

你不能自动化它,但你当然可以在一个位置拥有逻辑:

const type* func_const (const type*)
{
    /* actual implementation goes here */
}

type* func (type* param)
{
    /* just call the const function where the "meat" is */
    return (type*)func_const(param);
}
Run Code Online (Sandbox Code Playgroud)