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.
CodePudding user response:
#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 &&