2010-07-24 94 views
2

假设在C非const版本我有功能Ç常量/相同功能

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

,使得它们都具有完全相同的内部逻辑。

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

+0

你可以改为C++吗? – Anycorn 2010-07-24 17:42:46

+0

没有(fillllller) – 2010-07-24 17:44:05

回答

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

做这样的标准C库函数做,只是把一个const限定参数符合条件的结果。 (见strchr,strstr等)这是最实用的。

+1

但打破了类型安全。 – 2010-07-24 17:55:15