开发者

C const/non-const versions of same function

Suppose in C I have the functions

type* func (type*);
const type* func_const (const type*);

such that they both have the exact same internal logic.

Is there a way I can merge the two into one function, where if given a const type, it returns a const type; and if given a non-const type, it returns a non-const type? If not, 开发者_运维问答what is a good way of dealing with this? Define one in terms of the other via explicit casting perhaps?


You can't automate it, but you can certainly have the logic in a single location:

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


Do like the standard C library functions do and just take a const-qualified argument while returning a non-const-qualified result. (See strchr, strstr, etc.) It's the most practical.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜