Reputation: 1
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?
Upvotes: 2
Views: 466
Reputation: 215193
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.
Upvotes: 2
Reputation: 20726
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);
}
Upvotes: 10