Search code examples
c++overloading

C++ Is it possible to overload a function so that its argument accept literal and reference respectively?


I'm having a problem with using C++ overloading and was wondering if anybody could help.

I'm trying to overload functions so that its argument accept reference and literal respectively.

For example, I want to overload func1 and func2 to func:

int func1 (int literal); 
int func2 (int &reference);

and I want to use func in this situations:

func(3);   // call func1
int val = 3;
func(val); // I want func2 to be called, but ambiguous error

Is there any way to overload these functions?

thanks! Any help would be appreciated! sorry for poor english.


Solution

  • Literals and temporary values can only be passed as const references while named values will prefer a non-const reference if available. You can use this with either & or && to create the 2 overloads.

    For why and more details read up on rvalues, lvalues, xvalues, glvalues and prvalues.

    The code below shows which function overload will be used for the most common cases, the first 2 being the ones you asked about:

    #include <iostream>
    
    void foo1(int &) { std::cout << "int &\n"; }
    void foo1(const int &) { std::cout << "const int &\n"; }
    
    void foo2(int &) { std::cout << "int &\n"; }
    void foo2(const int &) { std::cout << "const int &\n"; }
    void foo2(int &&) { std::cout << "int &&\n"; }
    void foo2(const int &&) { std::cout << "const int &&\n"; }
    
    int bla() { return 1; }
    
    int main() {
        int x{}, y{};
        std::cout << "foo1:\n";
        foo1(1);
        foo1(x);
        foo1(std::move(x));
        foo1(bla());
        std::cout << "\nfoo2:\n";
        foo2(1);
        foo2(y);
        foo2(std::move(y));
        foo2(bla());
    }
    

    Output:

    foo1:
    const int &
    int &
    const int &
    const int &
    
    foo2:
    int &&
    int &
    int &&
    int &&