tags:

views:

79

answers:

2

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?

+9  A: 

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);
}
Jim Buck
+1  A: 

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.

R..
But breaks type-safety.
Ben Voigt