Is there a way to let the compiler distinguish whether the passed variable is a reference or not, without explicitly specifying it using e.g. <int &>
? The following example displays '1', whereas I expected a '2':
template <typename Type>
void fun(Type)
{
cout << 1 << '\n';
}
template <typename Type>
void fun(Type &)
{
cout << 2 << '\n';
}
int main()
{
int x = 0;
int &ref = x;
fun(ref);
}
I also tried to use std::ref
, but I don't get it to work.
template <typename Type, typename = std::enable_if_t<!std::is_reference<Type>::value>>
void fun(Type)
{
std::cout << 1 << '\n';
}
template <typename Type, typename = std::enable_if_t<std::is_reference<Type>::value>>
void fun(Type &)
{
std::cout << 2 << '\n';
}
int main() {
int x = 0;
int &ref = x;
fun<int&>(ref); // Call the one that you want, and don't leave the compiler decide which one you meant
return EXIT_SUCCESS;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With