How to "merge" 2 functions (const & non-const i/o) into one?

199 Views Asked by At

Is there a syntax for merging the following 2 functions into one, so that if input is const, result is const, and if input is non-const, result is non-const?

char* f1(char* x) {
    return x+1;
}

const char* f2(const char* x) {
    return x+1;
}

3

There are 3 best solutions below

1
On

This

char* f1(char* x) {
    return x+1;
}

const char* f1(const char* x) {   // rename f2->f1
    return x+1;
}

Does not make it "one function", but it is one set of overloads and for the user it shouldnt matter that it actually is more than one function unless they try to take the address.

There are ways to avoid duplication of the implementation, perhaps the most simple is to implement the non-const overload in terms of the const one:

const char* f1(const char* x) {
    return x+1;
}

char* f1(char* x) {
    return const_cast<char*>(f1(static_cast<const char*>(x)));
}

In the second overload x points to a non-const char, hence it is ok to cast away the constness from result of the other overload.

0
On

You can make a function template as shown below:

template <typename T>
auto foo(T *ptr)
requires(std::is_same_v<std::remove_const_t<T>, char>)
{
    return ptr+1;
}
0
On

Simple template:

#include <iostream>


template <typename T>
T* f(T* p)
{
    return p + 1;
}


int main()
{
    // const char pointer:
    const char cca[]{ "Hello" };
    const char* ccp{ f(cca) };
    std::cout << *ccp << std::endl; // 'e'
    
    // char pointer:
    char ca[6]{ "World" };
    char* cp{ f(ca) };
    std::cout << *cp << std::endl; // 'o'
}

Demo